Search code examples
c#iequalitycomparer

IEqualityComparer string value within object


I quite possibly am doing this the wrong way but;

I have a list of objects in LINQ;

MyObj
  string name
  string somethingElse

List<MyObj> myObjects;

Now I'm trying to see if any object in that list has a string value;

So I have;

if (Model.myObjects.Contains("thisobject", new MyObjComparer()))
{
}

In the comparer I have;

public class MyObjComparer: IEqualityComparer<MyObj>
{
    public bool Equals(string containsString, MyObj obj)
    {
        return obj.name == containsString;
    }
}

How can I use a comparer to check against a string value in an objects field?


Solution

  • An easier method is to do this:

    if (Model.myObjects.Any(o => o.name == "thisobject"))
    {
    }