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?

4
  • 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. Commented Sep 21, 2010 at 5: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: stackoverflow.com/questions/1044236/… Commented Sep 21, 2010 at 5:51
  • By the way, you must tell others what do you want if there is A,B,A in the list. Commented Sep 21, 2010 at 6:04
  • @ danny Chen : That scenerio will not occur..... Commented Sep 21, 2010 at 6:16

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer. But you forgot the "-" in the op's question.
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);

1 Comment

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".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.