Thorin Oakenshield
Thorin Oakenshield

Reputation: 14682

Manipulating List<String> using Linq in C#

i've a List< String> like

   List<String> ListOne = new List<string> { "A-B", "B-C" };

i need to split each string if it contains '-' and add to the same list

So the result will be like

 { "A-B", "B-C","A","B","C" };

Now i'm using like

       for (int i = 0; i < ListOne.Count; i++)
        {
            if (ListOne[i].Contains('-'))
            {
               List<String> Temp = ListOne[i].Split('-').ToList();
               ListOne= ListOne.Union(Temp).ToList();
            }
        }

is there any way to do this using LINQ?

Upvotes: 3

Views: 756

Answers (2)

JaredPar
JaredPar

Reputation: 754725

Try the following

List.AddRange(
  ListOne
    .Where(x => x.Contains("-"))
    .SelectMany(x => x.Split('-'))
    .Distinct()
    .ToList());

Upvotes: 3

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68687

ListOne.Union(ListOne.SelectMany(i => i.Split('-')))

Upvotes: 4

Related Questions