比较列表中的每个元素 [英] Comparing each element with each other element in a list

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

问题描述

编写将遍历列表中每个2元素组合的控件结构的最佳方法是什么?

What is the best way to write a control structure that will iterate through each 2-element combination in a list?

示例:

{0,1,2}

我想让一个代码块运行三次,每次运行一次:

I want to have a block of code run three times, once on each of these:

{0,1}
{1,2}
{0,2}

我尝试了以下

foreach (int i in input)
{
    foreach (int j in input.Where(o => o != i))
    {
        //Execute code
    }
}

但是,当列表具有两个相同的元素时,此功能将无效.与

However, this won't work when a list has two of the same elements. With

{0,2,0}

我仍然想比较元素00.该值无关紧要.

I would still want to compare elements 0 and 0. The value is irrelevant.

推荐答案

听起来您可能想要以下东西:

It sounds like you might want something like:

for (int i = 0; i < list.Count - 1; i++)
{
    for (int j = i + 1; j < list.Count; j++)
    {
        // Use list[i] and list[j]
    }
}

您肯定可以使用LINQ做到这一点:

You definitely can do this with LINQ:

var pairs = from i in Enumerable.Range(0, list.Count - 1)
            from j in Enumerable.Range(i + 1, list.Count - i)
            select Tuple.Create(list[i], list[j]);

我不确定它是否更清晰...

I'm not sure it's any clearer though...

另一种方法效率较低,但可能更清晰:

Another alternative which is less efficient, but potentially clearer:

var pairs = from i in Enumerable.Range(0, list.Count - 1)
            let x = list[i]
            from y in list.Skip(i + 1)
            select Tuple.Create(x, y);

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

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