使用 LINQ 获取列表中的所有对

Get all pairs in a list using LINQ(使用 LINQ 获取列表中的所有对)
本文介绍了使用 LINQ 获取列表中的所有对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得列表中所有可能的项目对(顺序不相关)?

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

例如如果我有

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

我想得到这些元组:

var pairs = {
   new Tuple(1, 2), new Tuple(1, 3), new Tuple(1, 4),
   new Tuple(2, 3), new Tuple(2, 4)
   new Tuple(3, 4)
}

推荐答案

对 cgeers 答案进行轻微的重新表述,以获得你想要的元组而不是数组:

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);

(如果需要,请使用 ToListToArray.)

(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);

这两个实际上都会考虑 n2 个值而不是 n2/2 个值,尽管它们最终会得到正确的答案.另一种选择是:

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));

... 但这使用了可能未优化的Skip.老实说,这可能无关紧要 - 我会选择最适合您使用的那个.

... 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.

这篇关于使用 LINQ 获取列表中的所有对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)