Reputation: 22760
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?
Upvotes: 3
Views: 4863
Reputation: 78840
An easier method is to do this:
if (Model.myObjects.Any(o => o.name == "thisobject"))
{
}
Upvotes: 10
Reputation: 5239
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
}
Upvotes: 2
Reputation: 82913
You can use FindAll method as follows:
foreach(var item in Model.myObjects.FindAll(x=>x.Contains("thisobject")))
{
//Do your stuff with item
}
Upvotes: 2