开发者

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 开发者_JAVA百科do this using LINQ?


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


Try the following

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜