Try this:
var q = from item in lstMyTable
group item by item.ItemDate.ToString("MM/dd/yyyy HH:mm") into ItemGroup
select new
{
Description = ItemGroup.First().Description,
Date = ItemGroup.OrderBy(x => x.ItemDate).First().ItemDate
};
The above linq query groups by date + hour + minutes, ignoring seconds. The OrderBy
applied to ItemGroup
ensures that we get the mininum date, as described in the OP.
With this input:
List<MyTable> lstMyTable = new List<MyTable>()
{
new MyTable() { Description = "TEST s", ItemDate = new DateTime(2014, 12, 4, 16, 27, 11) },
new MyTable() { Description = "TEST s", ItemDate = new DateTime(2014, 12, 4, 16, 27, 12) },
new MyTable() { Description = "TEST s", ItemDate = new DateTime(2014, 12, 4, 16, 27, 13) },
new MyTable() { Description = "TEST s", ItemDate = new DateTime(2014, 12, 4, 17, 21, 11) },
new MyTable() { Description = "TEST s", ItemDate = new DateTime(2014, 12, 4, 17, 21, 12) },
new MyTable() { Description = "TEST s", ItemDate = new DateTime(2014, 12, 4, 17, 21, 13) }
};
you get this result:
[0] = { Description = "TEST s", Date = {4/12/2014 4:27:11 pm} }
[1] = { Description = "TEST s", Date = {4/12/2014 5:21:11 pm} }
If you want to also group by description then simply substitue the group by
clause with sth like this:
group item by new
{
a = item.ItemDate.ToString("MM/dd/yyyy HH:mm") ,
b = item.Description
} into ItemGroup
Finally, by converting the Datetime
field to Ticks
, you can fiddle with the required time distance between separate records, e.g.
group item by new
{
a = item.ItemDate.Ticks.ToString().Substring(0, item.ItemDate.Ticks.ToString().Length - 10), // instead of .ToString("MM/dd/yyyy HH:mm") ,
b = item.Description
} into ItemGroup
You can play around by varying the number of digits subtracted from item.ItemDate.Ticks
, substituting e.g. 10 with 9 or 8, etc.