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?
CodePudding user response:
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