获取所有成对使用LINQ名单 [英] Get all pairs in a list using LINQ

查看:123
本文介绍了获取所有成对使用LINQ名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到的所有可能的对项目的列表中怎么办(为了不相关的)?



例如。如果我有



  VAR列表= {1,2,3,4}; 



我想获得这些元组:

  VAR对= {
新的元组(1,2),新的元组(1,3),新的元组(1,4),
新的记录( 2,3),新的元组(2,4)
新的元组(3,4)
}


解决方案

cgeers轻微改写回答得到你想要的,而不是数组的元组:

  VAR组合名单中的
,其中ITEM1和LT来自Item1 =列表中的
从ITEM2; ITEM2
选择Tuple.Create(ITEM1,ITEM2);



(使用了ToList 或<$ C $ 。C>的ToArray )



在非查询表达形式(有点重新排序):

  VAR组合= list.SelectMany(X =>清单(X,Y)=> Tuple.Create(X,Y))
。凡(元组=> tuple.Item1< tuple.Item2);



这两个实际上会考虑ñ 2 值而不是n 2 / 2的值,虽然他们会用正确的答案结束。另一种方法是:



  VAR组合= list.Select((价值指数)=>新建{值,指数} )
.SelectMany(X => list.Skip(x.index + 1),
(X,Y)=> Tuple.Create(x.value,y)的);



...但是这使用跳过这可能的的不进行优化。它可能并不重要,说实话 - 我会选择哪一个最适合您的使用情况


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 get these tuples:

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

解决方案

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.Select((value, index) => new { value, index })
                       .SelectMany(x => list.Skip(x.index + 1),
                                   (x, y) => Tuple.Create(x.value, 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.

这篇关于获取所有成对使用LINQ名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆