Reputation: 14702
I'm having a list of string
List<String> MyList=new List<String>{ "A,B" , "C,D,E" , "F,G" };
I need to convert the List "MyList" into the following format
"A-B"
"B-A"
"C-D"
"C-E"
"D-C"
"D-E"
"E-C"
"E-D"
"F-G"
"G-F"
Now i'm using something like spliting each item by "," and then adding that to a new list, then taking combination and then performing union operation among all the lists.
Is there any way to do this using LINQ?
Upvotes: 1
Views: 187
Reputation: 3011
Something like this, assuming no repeats in each list.
from a in new List<String>{ "A,B" , "C,D,E" , "F,G" }
select a.Split(',') into b
from c in b
from d in b
where c != d
select c + "-" + d
A bit more awkward to allow duplicates:
(new List<String>{ "A,B" , "C,D,E" , "F,G" }).Select(csv =>
csv.Split(',')
.SelectMany((a,i) => csv.Split(',').Select((b,j) => new { a, i, b, j } ))
.Where(r => r.i != r.j)
.Select(r => r.a + "-" + r.b))
Upvotes: 3
Reputation: 11675
var items = new List<string>{ "A,B" , "C,D,E" , "F,G" };
var results = from x in items
let y = x.Split(',')
from z1 in y
from z2 in y
where z1 != z2
select string.Format("{0}-{1}", z1, z2);
Upvotes: 2