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 获取列表中的所有对
基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
