score:1
Accepted answer
I will propose 2 solutions for your problem, depend on the length of your list one will be better.
Initialize :
var myList = new List<DataRecord>
{
new DataRecord
{
MeasurementDate = new DateTime(2019, 1, 31, 11, 50, 0)
},
new DataRecord
{
MeasurementDate = new DateTime(2019, 1, 31, 17, 21, 0)
},
new DataRecord
{
MeasurementDate = new DateTime(2019, 1, 31, 17, 59, 0)
},
new DataRecord
{
MeasurementDate = new DateTime(2019, 1, 31, 10, 54, 0)
},
new DataRecord
{
MeasurementDate = new DateTime(2019, 1, 31, 11, 54, 0)
},
};
List<DataRecord> result = new List<DataRecord>();
Solution 1 :
var minimumMinutes = myList.Min(x => x.MeasurementDate.Hour * 60 + x.MeasurementDate.Minute);
var maximumMinutes = myList.Max(x => x.MeasurementDate.Hour * 60 + x.MeasurementDate.Minute);
for (int minutes = minimumMinutes; minutes < maximumMinutes; minutes++)
{
var list = myList.Where(x =>
x.MeasurementDate.Hour * 60 + x.MeasurementDate.Minute <= minutes + 60 &&
x.MeasurementDate.Hour * 60 + x.MeasurementDate.Minute >= minutes);
if (result.Count < list.Count())
{
result = list.ToList();
}
}
Solution 2 :
foreach (var dataRecord in myList)
{
var minutes = dataRecord.MeasurementDate.Hour * 60 + dataRecord.MeasurementDate.Minute;
var before = myList.Where(x =>
x.MeasurementDate.Hour * 60 + x.MeasurementDate.Minute >= minutes - 60 &&
x.MeasurementDate.Hour * 60 + x.MeasurementDate.Minute <= minutes).ToList();
var after = myList.Where(x =>
x.MeasurementDate.Hour * 60 + x.MeasurementDate.Minute <= minutes + 60 &&
x.MeasurementDate.Hour * 60 + x.MeasurementDate.Minute >= minutes).ToList();
if (before.Count > result.Count ||
after.Count > result.Count)
{
result = before.Count > after.Count ? before.ToList() : after.ToList();
}
}
score:1
As I mentioned in comments this code is not performance efficient, but this will do the trick.
// DummyData
List<DateTime> dates = new List<DateTime>
{
DateTime.Parse("2019/01/31 11:50"),
DateTime.Parse("2019/02/02 17:21"),
DateTime.Parse("2019/03/01 17:59"),
DateTime.Parse("2019/03/12 10:54"),
DateTime.Parse("2019/05/28 11:15"),
};
// Storage for final Output
List<DateTime> finalOp = new List<DateTime>();
// Main logic goes here
// foreach Hour in list we will compare that with every other Hour in list
// and it is in 1 hour range we will add it to list
foreach (DateTime dateTime in dates)
{
List<DateTime> temp = new List<DateTime>();
foreach (DateTime innerDateTime in dates)
{
// find the difference between two hours
var timeSpan = dateTime.TimeOfDay - innerDateTime.TimeOfDay;
// add it to same list if we have +/- 1 Hour difference
if (timeSpan.TotalHours <= 1 && timeSpan.TotalHours >= -1)
{
temp.Add(innerDateTime);
}
}
// once we have final group for date we will check if this has maximum number of common dates around
// if so replace it with previous choice
if (finalOp.Count < temp.Count)
{
finalOp = temp;
}
}
// print the results
foreach (var data in finalOp)
{
Console.WriteLine(data.ToShortTimeString());
}
score:0
For the 10,000 items of myList
collection this solution can be fast:
private static List<DataRecord> Get(List<DataRecord> myList)
{
var ordered = myList.OrderBy(x => x.MeasurementDate.TimeOfDay).ToList();
int i = 0;
int count = myList.Count();
var temp =
(from s in ordered
let index = ++i
let next = ordered.ElementAtOrDefault(index != count ? index : 0)
select new
{
Cur = s.MeasurementDate,
Diff = index != count
? (next.MeasurementDate.TimeOfDay - s.MeasurementDate.TimeOfDay).TotalMinutes
: 24 * 60 - (ordered.ElementAtOrDefault(count - 1).MeasurementDate.TimeOfDay - ordered.ElementAtOrDefault(0).MeasurementDate.TimeOfDay).TotalMinutes
}).ToList();
Dictionary<int, int> dict = new Dictionary<int, int>();
count = 0;
double minutes = 0;
for (int index = 0; index < temp.Count(); index++)
{
for (int j = index; j < temp.Count(); j++)
{
minutes += temp[j].Diff;
if (minutes > 60)
{
dict.Add(index, count);
count = 0;
minutes = 0;
break;
}
else
{
count++;
}
}
}
var max = dict.First(d => d.Value == dict.Values.Max());
var finalResult = ordered.Skip(max.Key).Take(max.Value + 1).ToList();
return finalResult;
}
Please note it returns ordered results.
Source: stackoverflow.com
Related Articles
- Select group from a List<T> matching a condition that cannot be directly specified on a property
- Entity framework Select first item in group that satisfies condition or just first item
- Select one of each matching results from group last record from date
- Linq - How to select items from a list that contains only items of another list?
- C# type arguments cannot be inferred from usage in Select with multiple returns
- Enumerable.Empty<T>().AsQueryable(); This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code
- LINQ: Select all from each group except the first item
- LINQ - type arguments cannot be inferred from the usage in a select
- Which LINQ query to select rows from 1 table that are not in another table
- Group items and select specific item from each group with LINQ
- how to select top 1 from each group after order by
- The given value of type String from the data source cannot be converted to type int of the specified target column
- Linq intersect or join to return items from one collection that have matching properties to another?
- How to use Linq to select and group complex child object from a parents list
- LINQ to select a column with max date from a group
- Linq select strings from list when condition is met and save the index
- c# Linq - Select Top 2 from Each Group
- How to select objects from a list that has a property that matches an item in another list?
- LINQ Select - CS0411 The type arguments cannot be inferred from the usage - What am I doing wrong?
- Select a field that is not in Group By clause in LINQ
- LINQ select one bool from condition over multiple rows
- Linq select all numbers that are in any interval from another list of intervals
- creating Linq to sqlite dbml from DbLinq source code
- How to select multiple columns from datatable in linq group by?
- Get 3 results from searching a List of xy Points that satisfies a condition c#
- Select a matching string randomly from a list using LINQ
- Linq select from list where property matches a condition
- Select 1 column from a Group By LINQ query
- How to select Columns using where condition from one DataTable to another in C#
- How to effectively select all values matching given pattern from a list of struct?
- Using C# LINQ to concat a filtered List<object> to List<string>
- Groupby multiple date properties by month and year in LINQ
- Exclude collection for removal, Linq
- How to insert user with existing role-object using EF?
- Read a generic List<T> with parent/child hierarchy into a datatable preserving the parent/child hierarchy
- Join 3 tables or more
- LINQ: Can't filtering List<Model> data by .Contains
- LINQ Remove all Users where UserId is in the list
- How to use order by when using the group by in LINQ
- What kind of syntax/technology is used to count items in the cart in a MVC 4 Application
- How do I invoke an extension method using reflection?
- Query entity select, inner join and count
- LinqToSql with dates problem
- Linq query with outer join doesn't return expected result
- List of TimeSpan to String Array using LINQ
- Using OrderBy in Linq
- Linq query to select only common items in two lists
- Linq OrderBy Attribute Value and Group
- How to calculate an ETA for a LINQ pipeline to complete?
- get values from a nested dictionary using lambda values of the dictionary are ArrayList of ArrayList