开发者

C# Use object's property rather than reference for List.Contains()

开发者 https://www.devze.com 2023-03-16 10:09 出处:网络
I have something like: public class MyClass { public string Type { get; set; } public int Value { get; set; }

I have something like:

public class MyClass
{
  public string Type { get; set; }
  public int Value { get; set; }
}

and then I have:

List<MyClass> myList = new List<MyClass>()

// ... Populate myList

if (myList.Contains("testType"))
{
  // Do开发者_JAVA百科 something
}

In the above code, I want myList.Contains() to match on the Type property rather than the MyClass object reference. How do I achieve this? Do I use the IComparable or ICompare interface, do I override MyClass.Equals(), or is it sufficient to override the string cast of MyClass?

Edit: After doing some tests with overriding Equals() and the string cast of MyClass, implementing ICompare and IComparable, I have found that none of these methods work. Actually, it seems like what would work is if I were to override the MyClass cast of string, something like myList.Contains((MyClass)"testType"). However I think I like The Scrum Meister's answer better :)


You can use the Any extension method:

if (myList.Any(x => x.Type == "testType"))
{
  // Do something
}


In additional to @The Scrum Meister's answer, if you are using C#2.0 you can use List<T>.Find

MyClass target = myList.Find(m => m.Type == "testType");
if (target != null)
{
  // Do something to the target
}


To clarify on The Scrum Meister's answer, the condition you provided won't even compile, if I am reading it correctly. You're seeing if a list comprised of MyClass objects contains a string, so that won't work.

It seems like what you really want to do is check and see if any instance of a MyClass object that is in that list has a Type property that matches your desired type.

For clarity's sake, though, I'd redefine the MyClass class like so:

public class MyClass {
    public Type MyType { get; set; }
    public int Value { get; set; }
}

Then your condition would be:

if(myList.Any(x => x.MyType == typeof(SomeClass)) { // put the real class name in the typeof()
    // Do something
}

Hope that explains things a bit clearer.


If you implement IEquatable<T>, you will basically override the Object.Equals() method. According to MSDN you should explicitly override the Object.Equals method. You can then do something like:

void Add (MyClass testCls)
{
    var myCls = myList.Where(x => x.Equals(testCls)).Select(x => x).FirstOrDefault();

    if (myCls == null)
    {
            // then myList does not contain the object you want to add
            myList.Add(testCls);
    }
}

For more on IEquatable<T>: MSDN IEquatable(T)
The advantage to this is that you are actually checking against the Type property of other list contents - if that is what you are looking to do.

0

精彩评论

暂无评论...
验证码 换一张
取 消