Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# split list into two lists using bool function [duplicate]

Tags:

c#

list

filter

Say I have a List<string> listOfStrings and I want to divide this list into two lists based on some predicate. E.g., the first list should contain all strings that start with a letter, and second is a list of strings that don't.

Now I would do this like this:

var firstList = listOfStrings.Where(str => predicate(str));
var secondList = listOfStrings.Where(str => !predicate(str));

Is there a better way of doing this in one line?

like image 947
eddyP23 Avatar asked Mar 19 '26 14:03

eddyP23


1 Answers

You can use Linq's GroupBy():

var splitted = listOfStrings.GroupBy(s => Char.IsLetter(s[0]));

And with your predicate, it would be:

Func<string, bool> predicate;

var splitted = listOfStrings.GroupBy(predicate);

Usage:

The easiest way would be to convert the grouped data into a Dictionary<bool, IEnumerable<string>>, when the key is a bool that denotes whether the items in it start with a letter:

var splitted = list.GroupBy(x => Char.IsLetter(x[0]))
                   .ToDictionary(x => x.Key, z => z.ToArray());  

var startWithLetter = splitted[true];
var dontStartWithLetter = splitted[false];

Of course, there are many ways to massage the data into your desired structure, but the above is pretty concise in my opinion.

See MSDN

like image 192
haim770 Avatar answered Mar 21 '26 03:03

haim770