Linq group by question
I have a datasource with columns id,myname,eventime,ceasetime. I need to find out duplicate date ranges for a given Key. I tried to use -
(from data1 in myDatasource
from data2 in myDatasource
where data1.SeqId != data2.SeqId
&& data1.myname ==data2.myname
where data1.Event_Time <=data2.Cease_Time
&& data1.Cease_Time > data2.Event_Time
select data1).Distinct();
but this is too slow, as i think, each row is compared with all the rest of rows. What I want to do is to first group by myName and then apply the where 开发者_运维技巧condition. The thing is the where condition can return multiple rows, Can anybody suggest someway
regards
var lookup = from data1 in myDataSource
group by myDataSource.myName into g
where g.Count() > 1
select g;
This should do it. It'll return a Lookup of your objects grouped by their name, where there is more than one element for each name. If you want to flatten this back out, take lookup
and call SelectMany on it:
var flatEnumerable = lookup.SelectMany(g=>g); //ToList(), ToArray(), etc will get you a concrete collection
精彩评论