Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ to split items within a list

Tags:

c#

linq

I want to separate each item in a list, but also within each item, split the item if it contains :

eg.

string[] names = {"Peter:John:Connor","Paul","Mary:Blythe"};
name.Dump();

Will show:

Peter:John:Connor
Paul
Mary:Blythe

However, is there any LINQ that I can use, which will provide the following list:

Peter
John
Connor
Paul
Mary
Blythe

I can do this using:

foreach (var person in names)
{
    x = person.split(":").ToList();
    foreach (var personinlist in x)
    {
        // personinlist
    }
}          

...but that seems very long winded, when I'm certain LINQ could be more elegant.

like image 702
Mark Avatar asked Jun 21 '13 11:06

Mark


1 Answers

Use SelectMany to flatten results of splitting each name by :

names.SelectMany(n => n.Split(':'))
     .Dump();
like image 76
Sergey Berezovskiy Avatar answered Oct 03 '22 14:10

Sergey Berezovskiy