Reputation: 14682
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
Reputation: 754725
Try the following
List.AddRange(
ListOne
.Where(x => x.Contains("-"))
.SelectMany(x => x.Split('-'))
.Distinct()
.ToList());
Upvotes: 3