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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With