Get all pairs in a list using 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);
(如果需要,请使用 ToList
或 ToArray
.)
(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 获取列表中的所有对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 LINQ 获取列表中的所有对


基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01