Question

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?

Was it helpful?

Solution

An easier method is to do this:

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

OTHER TIPS

You can use FindAll method as follows:

foreach(var item in Model.myObjects.FindAll(x=>x.Contains("thisobject")))
{
 //Do your stuff with item  
}

The equality comparer is only good to tell if two objects of the same type are equal. I don't know your use-case, but could you simply do something like

if (Model.myObjects.Where(x => x.name == "thisobject").Any())
{ 
    // Do something
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top