Search code examples
c#loopspermutationc#-11.0

C# How to permutate all elements with each others in a List of string


I have a string list and i want all permutations of all elements with each others

Example :

var myList = new List<string>{ "AB", "CD", "EF", "GK" };

and as result i want a string like this.

var resultStr = "ABCD,ABEF,ABGK,CDAB,CDEF,CDGK,EFAB,EFCD,EFGK,GKAB,GKCD,GKEF";

note that resultStr doesnt include "ABAB","CDCD","EFEF","GKGK"

is there any short way to do this except double for/foreach loops?


Solution

  • Q: is there any short way to do this except double for/foreach loops?

    Yes, you can use LINQ.

    Here's the LINQ syntax expression for your result:

    var myList = new List<string>{ "AB", "CD", "EF", "GK" };
    var result = from a in myList from b in myList where a != b select a+b;
    var resultStr = string.Join(",", result);
    Console.WriteLine(resultStr);
    

    You can also use the LINQ extension methods:

    var myList = new List<string>{ "AB", "CD", "EF", "GK" };
    var result = myList.SelectMany(a => myList.Where(b => b != a).Select(b => a + b));
    var resultStr = string.Join(",", result);
    Console.WriteLine(resultStr);
    

    Both will output

    ABCD,ABEF,ABGK,CDAB,CDEF,CDGK,EFAB,EFCD,EFGK,GKAB,GKCD,GKEF
    

    .NET Fiddle so you can try it