我正在尝试将双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列表中。这是一本字典。
答案 0 :(得分:1)
如果你有IEnumberable
KeyValuePair
s,那么你可以这样做:
public bool AreAllSame(IEnumberable<KeyValuePair<Int64, MyObject>> list)
{
return list.Select(kv => kv.Value).Distinct().Count == 1;
}
不确定它是否真的优化但是,它更短! : - ]
当然,无论你比较什么,都需要具有可比性。