优化比较多个事物的foreach循环

时间:2012-11-15 15:20:12

标签: c# dictionary

  

可能重复:
  Optimizing Double foreach loop

我正在尝试将双foreach循环转换为单个foreach循环

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定义为

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

无论如何使用一个循环来执行此操作?当它们完全相同时,我将它们添加到Int64列表中。这是一本字典。

1 个答案:

答案 0 :(得分:1)

如果你有IEnumberable KeyValuePair s,那么你可以这样做:

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

不确定它是否真的优化但是,它更短! : - ]

当然,无论你比较什么,都需要具有可比性。