Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

c# - Select all unique combinations of a single list, with no repeats, using LINQ

I have a list of numbers, and I need to create every possible unique combination of the numbers in the list, without repeats, using a LINQ query. So, for example, if I have { 1, 2, 3 }, the combinations would be 1-2, 1-3, and 2-3.

I currently use two for loops, like so:

for (int i = 0; i < slotIds.Count; i++)
{
    for (int j = i + 1; j < slotIds.Count; j++)
    {
        ExpressionInfo info1 = _expressions[i];
        ExpressionInfo info2 = _expressions[j];

        // etc...
    }
}

Is it possible to convert these two for loops to LINQ?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sure - you can do it in a single call to SelectMany with an embedded call to Skip:

var query = slotIds.SelectMany((value, index) => slotIds.Skip(index + 1),
                               (first, second) => new { first, second });

Here's an alternative option, which doesn't use quite such an esoteric overload of SelectMany:

var query = from pair in slotIds.Select((value, index) => new { value, index })
            from second in slotIds.Skip(pair.index + 1)
            select new { first = pair.value, second };

These do basically the same thing, just in slightly different ways.

Here's another option which is much closer to your original:

var query = from index in Enumerable.Range(0, slotIds.Count)
            let first = slotIds[index] // Or use ElementAt
            from second in slotIds.Skip(index + 1)
            select new { first, second };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...