我有一个包含许多对象的列表。我想在此列表中找到一个对象,每个属性都等于列表中的对象。 例如:
list.Add(object1,object2,object3,object4);
// for example I want found object3
//list.find(object3)
我有一个问题我必须检查除了一个属性之外的所有属性。例如,对象具有此属性(int prop1,int prop2,int prop3)。我想找到prop1和prop2等于列表中任何项目的对象;
答案 0 :(得分:2)
覆盖Equals方法将是一种方法。
或者您可以尝试编写一个find函数使用反射来动态检查这些对象的属性。
答案 1 :(得分:1)
所以,似乎你想让List的Contains-Method适合你。
看看这里:MSDN List.Contains
根据它,你可以在你的对象中实现IEquatable来实现它。
希望有所帮助。 干杯 的Sascha
答案 2 :(得分:0)
始终采用Linq方式做事。例如:
var haystack = new List<Tuple<int, bool, string>>()
{
new Tuple<int, bool, string>(1, true, "one"),
new Tuple<int, bool, string>(2, false, "two"),
new Tuple<int, bool, string>(3, true, "three"),
new Tuple<int, bool, string>(4, true, "four")
};
var needle = new Tuple<int, bool, string>(3, true, "three");
var found =
haystack.FirstOrDefault(
t => t.Item1 == needle.Item1 && t.Item2 == needle.Item2 && t.Item3 == needle.Item3);
Assert.AreSame(haystack[2], found);
我运行此Assert.AreSame
测试。