Get all pairs in a list using LINQ

前端 未结 3 1202
攒了一身酷
攒了一身酷 2020-12-09 04:02

How do I get all possible pairs of items in a list (order not relevant)?

E.g. if I have

var list = { 1, 2, 3, 4 };

I would like to

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 05:03

    Slight reformulation of cgeers answer to get you the tuples you want instead of arrays:

    var combinations = from item1 in list
                       from item2 in list
                       where item1 < item2
                       select Tuple.Create(item1, item2);
    

    (Use ToList or ToArray if you want.)

    In non-query-expression form (reordered somewhat):

    var combinations = list.SelectMany(x => list, (x, y) => Tuple.Create(x, y))
                           .Where(tuple => tuple.Item1 < tuple.Item2);
    

    Both of these will actually consider n2 values instead of n2/2 values, although they'll end up with the correct answer. An alternative would be:

    var combinations = list.SelectMany((x, i) => list.Skip(i + 1), (x, y) => Tuple.Create(x, y));
    

    ... but this uses Skip which may also not be optimized. It probably doesn't matter, to be honest - I'd pick whichever one is most appropriate for your usage.

提交回复
热议问题