1

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?

Timwi
  • 65,159
  • 33
  • 165
  • 230
Thorin Oakenshield
  • 14,232
  • 33
  • 106
  • 146
  • Just a warning - you can expect this to get fairly expensive wrt. time as soon as you've more than a large handful (!) of elements in one of your strings. – Will A Sep 21 '10 at 05:49
  • not sure if you already have an iterative solution and you're just trying to find a more 'elegant' perspective, but here's a look at performance of one vs the other: http://stackoverflow.com/questions/1044236/nested-foreach-vs-lambda-linq-query-performancelinq-to-objects – Oren Mazor Sep 21 '10 at 05:51
  • By the way, you must tell others what do you want if there is `A,B,A` in the list. – Cheng Chen Sep 21 '10 at 06:04
  • @ danny Chen : That scenerio will not occur..... – Thorin Oakenshield Sep 21 '10 at 06:16

2 Answers2

3

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
  • 2,983
  • 1
  • 20
  • 18
2
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
  • 11,415
  • 1
  • 49
  • 51
  • 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 Sep 21 '10 at 06:19