Manipulating a <String> List Using Linq in C #

I have a list of <String> like

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

I need to split each line if it contains '-' and add to the same list

So, the result will be similar to

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

Now i use as

       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?

+3
source share
2 answers
ListOne.Union(ListOne.SelectMany(i => i.Split('-')))
+4
source

Try to execute

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

Source: https://habr.com/ru/post/1763200/


All Articles