Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading