优化双foreach循环 [英] Optimizing Double foreach loop

查看:134
本文介绍了优化双foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个双foreach循环,并希望通过使一个循环,而不是两个,以加快速度。



我们的想法是,它需要从字典一种元素和针对所有元素在词典



<$ P进行比较$ p> 的foreach(KeyValuePair<的Int64,字符串> KVP在originCounts)
{
的foreach(KeyValuePair<的Int64,字符串> testkvp在originCounts)
{
//运行比较上testkvp广告KVP
}
}

我想变成一个循环,有什么建​​议吗?


解决方案

您可以使用的 Enumerable.All 来检查是否所有的元素都是相同的:

  VAR firstID = originCounts.First()Value.UserID。 
布尔allEquals = originCounts.Skip(1)。所有(O = GT; o.Value.UserID == firstID);



看来,这是你真正想要的东西。



我刚刚挑选出你的类的字段在重复这个问题听起来合理的标识符。

 公共类MyObject的
{
公共字符串名字{搞定;组; }
公共字符串名字{获得;组; }
公众诠释用户名{搞定;组; }
公共字符串地址{搞定;组; }
}



修改:根据您的评论你想以确定的对象'字段的任何的是另一个对象的同一领域不同。

  。VAR第一= originCounts.First()值; 
布尔allEquals = originCounts.Skip(1)。所有(O = GT;
o.Value.FirstName == first.FirstName
和;&安培; o.Value.LastName ==第一.LastName
和;&安培; o.Value.UserID == first.UserID
和;&安培; o.Value.Address == first.Address);


I have a double foreach loop and want to speed it up by making it one loop instead of two.

The idea is that it takes one element from the dictionary and compares it against all elements in the dictionary

foreach (KeyValuePair<Int64, string> kvp in originCounts)
{
    foreach (KeyValuePair<Int64, string> testkvp in originCounts)
    {
    //Run Comparison on testkvp ad kvp
    }
}

I want to turn this into one loop, any suggestions?

解决方案

You can use Enumerable.All to check if all elements are the same:

var firstID = originCounts.First().Value.UserID;
bool allEquals = originCounts.Skip(1).All(o => o.Value.UserID == firstID);

It seems that this is what you actually want.

I've just picked out a field of your class in the duplicate question that sounds as a reasonable identifier.

public class MyObject 
{
    public string FirstName{ get; set; }
    public string LastName{ get; set; }
    public int UserID { get; set; }
    public string Address { get; set; }
}

Edit: According to your comment you want to determine if any of the objects' fields is different to the same field of another object.

var first = originCounts.First().Value;
bool allEquals = originCounts.Skip(1).All(o =>
                o.Value.FirstName == first.FirstName
             && o.Value.LastName  == first.LastName
             && o.Value.UserID    == first.UserID
             && o.Value.Address   == first.Address);

这篇关于优化双foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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