C # Use an object property, not a link for List.Contains ()

I have something like:

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

and then I:

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

// ... Populate myList

if (myList.Contains("testType"))
{
  // Do something
}

In the above code, I want it to myList.Contains()match the Type property, not the reference to the MyClass object. How do I achieve this? Do I use the interface IComparableor ICompare, do I override MyClass.Equals(), or is it enough to override the MyClass string?

Edit: after doing some tests with an override Equals()and a string MyClassthat implements ICompareand IComparable, I found that none of these methods work. It actually seems like this will work if I have to redefine the line MyClass, something like myList.Contains((MyClass)"testType"). However, I think I like The Scrum Meister better :)

+5
4

Any :

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

@The Scrum Meister , # 2.0, List<T>.Find

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

IEquatable<T>, Object.Equals(). MSDN, Object.Equals. - :

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);
    }
}

IEquatable<T>: MSDN IEquatable (T)
, Type - , .

0

Scrum Meister, , , , . , , MyClass, , .

It looks like you really want to check and see if any instance of the MyClass object that is on this list has a Type property that matches your desired type.

For clarity, I would override the MyClass class as follows:

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

Then your condition will be:

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

Hope this explains things a little clearer.

0
source

All Articles