在基于其他对象的列表中查找对象

时间:2012-02-22 06:35:24

标签: c#

我有一个包含许多对象的列表。我想在此列表中找到一个对象,每个属性都等于列表中的对象。 例如:

list.Add(object1,object2,object3,object4);
// for example I want found object3
//list.find(object3)

我有一个问题我必须检查除了一个属性之外的所有属性。例如,对象具有此属性(int prop1,int prop2,int prop3)。我想找到prop1和prop2等于列表中任何项目的对象;

3 个答案:

答案 0 :(得分:2)

覆盖Equals方法将是一种方法。

或者您可以尝试编写一个find函数使用反射来动态检查这些对象的属性。

请查看此处的文章:http://www.sidesofmarch.com/index.php/archive/2007/08/03/use-reflection-to-compare-the-properties-of-two-objects/

答案 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测试。