开发者

How to write the following group by and stripping time Linq query?

开发者 https://www.devze.com 2023-02-13 18:33 出处:网络
I have list like this- IdDate 101/03/2011 14:15:23.320 101/03/2011 16:15:23.320 101/03/2011 18:15:23.320

I have list like this-

Id    Date
1     01/03/2011 14:15:23.320
1     01/03/2011 16:15:23.320
1     01/03/2011 18:15:23.320
1     01/04/2011 19:15:23.320
2     01/03/2011 14:15:23.320
2     01/03/2011 15开发者_如何学JAVA:15:23.320
2     01/03/2011 18:15:23.320
2     01/05/2011 19:15:23.320
2     01/07/2011 20:15:23.320 

My desired output is -

Id    Date
1     01/03/2011
1     01/04/2011 
2     01/03/2011 
2     01/05/2011 
2     01/07/2011

So how can I group by on the first list on id and take only the date part and achieve the results above in Linq ?


Try something like this:

var result = yourList.GroupBy(item => 
    new {Id = item.Id, Date = item.Date.Date});

Basically, DateTime.Date strips the time information.

To loop through the result, you could do:

foreach(var grp in result)
{
    Console.WriteLine("{0}: {1}", grp.Key.Id, grp.Key.Date);
}


It appears that you want to group on the date and id, so you want to pull those out into a structure that you can group on. It's when you create this key structure that you can format the date using the Date property to create the grouping correctly:

from item in list
group item by new { item.Id, Date = item.Date.Date } into g
select g

At that point, the keys in the grouping returned will give you the list you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消