How to get "unordered choose two" permutation in a list of Strings in C#
i have a开发者_开发问答 list of string
List< String> lst
A
B
C
i need to add the combination of each item with other items to the list like
A
B
C
A-B
A-C
B-C
now i'm usign nested for loop for this.
is there any way to do this using linq?
thanks in advance
var sourceStrings = new List<string> {"A", "B", "C"};
var resultStrings = from a in sourceStrings
from b in sourceStrings
where a != b
select a + "-" + b;
foreach (var result in resultStrings)
Console.WriteLine(result);
In addition to previous answers, you might be interested in this article by Eric Lippert.
Just for the completeness, here the statement in fluent writing:
var sourceStrings = new List<string> { "A", "B", "C" };
var resultStrings = sourceStrings.SelectMany(a => sourceStrings,
(a, b) => new { a, b })
.Where(n => n.a != n.b)
.Select(n => n.a + "-" + n.b);
foreach (var result in resultStrings)
Console.WriteLine(result);
As I mentioned in my comment, I think what you want is either a permutation (where you reorder an ordered set) or a combination (where you get unordered subsets of an unordered set)
A general purpose library for doing all those things in C# can be found here:
http://www.codeproject.com/KB/recipes/Combinatorics.aspx
It's still not 100% clear to me what you want. Here are some options:
Let S be the set {A, B, C}
The Cartesian product S x S is AA, AB, AC, BA, BB, BC, CA, CB, CC. That is every possible combination of two elements, order matters, including duplicates.
"S permute 2" is AB, AC, BA, BC, CA, CB. That is, every possible combination of two elements, order matters, but no duplicates.
"S choose 2" is AB, AC, BC. That is, every possible combination of two elements, no order, no duplicates.
"Power set of S" is nothing, A, B, C, AB, AC, BC, ABC. That is, every possible combination of zero, one, two or three elements, no order.
You can generate a power set (if that's what you want to do) by counting in binary. Consider the numbers 0 through 7 in binary:
ABC
000 0 nothing
001 1 C
010 2 B
011 3 BC
100 4 A
101 5 AC
110 6 AB
111 7 ABC
So if you can count, you can generate the power set.
What is it you want, exactly?
精彩评论