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 获取列表中的所有对


- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 使用 rss + c# 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01