tags:

views:

48

answers:

2

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?

+3  A: 

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))
mancaus
Nice answer. But you forgot the "-" in the op's question.
John Buchanan
Fixed that now.. thx
mancaus
+1 for making the assumption explicit.
Timwi
+2  A: 
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);
Bennor McCarthy
This assumes that the strings between commas are unique. If the input list contains only "A,A" this will not output anything, but I would expect "A-A".
Timwi