tags:

views:

71

answers:

2

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?

+4  A: 
ListOne.Union(ListOne.SelectMany(i => i.Split('-')))
Yuriy Faktorovich
This won't add it to the same list, it will create a new `IEnumerable<T>`
JaredPar
@JaredPar if thats what he is looking for, yours is likely more efficient, but it's too late where I am to run tests.
Yuriy Faktorovich
@Yuriy, not worried at all about efficiency. Just noting the slight difference in what the OP was asking for. Yours could be easily modified to meet it.
JaredPar
@JaredPar I meant if he did `ListOne = new List(myExpression);`
Yuriy Faktorovich
+3  A: 

Try the following

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