优化foreach循环比较多个东西 [英] Optimizing foreach loop that compares multiple things

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

问题描述


可能重复:

优化双foreach循环

我正在尝试改变双重foreach循环到单个foreach循环

I am trying to turn a double foreach loop into a single foreach loop

foreach (KeyValuePair<Int64, MyObject> kvp in originCounts)
{
    foreach (KeyValuePair<Int64, MyObject> testkvp in originCounts)
    {
    //Run Comparison on testkvp ad kvp to see if all elements of object are the same
    }
}

MyObject定义如下

And MyObject is defined as such

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

有没有使用一个循环?当它们完全相同时,我将它们添加到Int64列表中。它是同一个字典。

Is there anyway to do this using one loop? When they are all the same, I add them to a list of Int64. It is the same dictionary.

推荐答案

如果您有 IEnumberable KeyValuePair 然后你可以这样做:

If you have a IEnumberable of KeyValuePairs then you could do something like this:

public bool AreAllSame(IEnumberable<KeyValuePair<Int64, MyObject>> list)
{
  return list.Select(kv => kv.Value).Distinct().Count == 1;
}

不知道这是否真的优化了,但是短! : - ]

Not sure whether it's really optimized but, it's shorter! :-]

当然,无论你进行什么比较都需要比较。

Of course, whatever you're comparing will need to be comparable.

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

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