Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split list into two lists with single LINQ statement [duplicate]

Tags:

c#

linq

I would like to split a list into two lists with a single LINQ statement. I'm currently doing this:

var listA = allItems.Where(item => item.IsUseful);
var listB = allItems.Except(listA);

But I want a single LINQ statement in query syntax that iterates over the original list only once, and returns an anonymous type with the two lists as properties (eg results.ListA; results.ListB).

like image 745
cyrus Avatar asked Aug 31 '26 23:08

cyrus


1 Answers

This will give you a Dictionary<bool, List<T>> with two lists, which you can easily get your lists with result[true] and result[false]:

var result = allItems.GroupBy(item => item.IsUseful)
                     .ToDictionary(x => x.Key,x => x.ToList());
like image 92
Selman Genç Avatar answered Sep 03 '26 14:09

Selman Genç



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!