C# How to split a List in two using LINQ

  • A+
Category:Languages

I am trying to split a List into two Lists using LINQ without iterating the 'master' list twice. One List should contain the elements for which the LINQ condition is true, and the other should contain all the other elements. Is this at all possible?

Right now I just use two LINQ queries, thus iterating the (huge) master List twice.

Here's the (pseudo) code I am using right now:

List<EventModel> events = GetAllEvents();  List<EventModel> openEvents = events.Where(e => e.Closer_User_ID == null); List<EventModel> closedEvents = events.Where(e => e.Closer_User_ID != null); 

Is it possible to yield the same results without iterating the original List twice?

 


You can use ToLookup extension method as follows:

 List<Foo> items = new List<Foo> { new Foo { Name="A",Condition=true},new Foo { Name = "B", Condition = true },new Foo { Name = "C", Condition = false } };    var lookupItems = items.ToLookup(item => item.Condition);         var lstTrueItems = lookupItems[true];         var lstFalseItems = lookupItems[false]; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: