3

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?

3 Answers 3

10

An easier method is to do this:

if (Model.myObjects.Any(o => o.name == "thisobject"))
{
}
2
  • Ah, I forgot about the overload of Any that takes a predicate delegate. +1 for that! Jan 25, 2011 at 0:13
  • Thanks for thisand for @Harry for pointing out that I'm not using comparer corrently.
    – griegs
    Jan 25, 2011 at 0:16
2

You can use FindAll method as follows:

foreach(var item in Model.myObjects.FindAll(x=>x.Contains("thisobject")))
{
 //Do your stuff with item  
}
1
  • I really only want to check to see if there is a single item in the list that matches. I know I can do a count but would like to use the comparer
    – griegs
    Jan 25, 2011 at 0:12
2

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
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.