过程中的每对的序列 [英] Process every pair in a sequence

查看:144
本文介绍了过程中的每对的序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找一个简洁的方式来处理每一个(无序)对元素在.NET中的序列。 我知道我可以嵌套循环做到这一点,但我一直在寻找的东西多一点可读性。

我想象像一个修改任何()扩展方法:

 的IEnumerable<交易>交易= ...
如果(transactions.AnyPair((一,二)=> first.UniqueID == second.UniqueID))
    扔 ...
 

或者,也许一个的foreach 风格之一:

 的IEnumerable< JigsawPiece>件= ...
pieces.ForEachPair((一,二)=> {
    TryFit(一,二);
});
 

这个问题已经被问了其他语言(如见<一href="http://stackoverflow.com/questions/942543/operation-on-every-pair-of-element-in-a-list">http://stackoverflow.com/questions/942543/operation-on-every-pair-of-element-in-a-list),但我正在寻找一个.NET解决方案。

解决方案

  VAR的查询=交易
             .SelectMany((VAL1,J)=&GT; transactions.Select((val2中,I)=&gt;新建{V1 = VAL1,V2 = val2中,I = I,当J = J}))
             。凡(X =&GT; x.i&LT; x.j);

VAR的结果= query.Select(X =&GT; x.v1.UniqueID == x.v2.UniqueID);
 

该执行的比较正确的次数。结果还包括索引匹配两种元素的I,J。

I'm looking for a concise way to process every (unordered) pair of elements in a sequence in .NET. I know I can do it with nested for loops, but I was looking for something a little more readable.

I was imagining something like a modified Any() extension method:

IEnumerable<Transaction> transactions = ...
if (transactions.AnyPair( (first, second) => first.UniqueID == second.UniqueID))
    throw ...

Or maybe a foreach-style one:

IEnumerable<JigsawPiece> pieces = ...
pieces.ForEachPair( (first, second) => {
    TryFit(first, second);
});

This question has been asked for other languages (e.g. see http://stackoverflow.com/questions/942543/operation-on-every-pair-of-element-in-a-list), but I'm looking for a .NET solution.

解决方案

var query = transactions
             .SelectMany((val1,j) => transactions.Select((val2,i) => new {v1=val1, v2=val2, i=i, j=j}))
             .Where(x => x.i < x.j);

var result = query.Select(x=> x.v1.UniqueID == x.v2.UniqueID);

This performs the comparison the correct number of times. The result also includes the indexes i, j of the two elements that matched.

这篇关于过程中的每对的序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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