IEqualityComparer string value inside an object

Maybe I'm doing it wrong, 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 this list has a string value;

So, I have a:

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

In comparison, I have:

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

How to use matching to check string value in objects field?

+3
source share
3 answers

A simpler way:

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

You can use the FindAll method as follows:

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

An equality comparator is only good for determining whether two objects of the same type are equal. I do not know your precedent, but you could just do something like

if (Model.myObjects.Where(x => x.name == "thisobject").Any())
{ 
    // Do something
}
+2
source

Source: https://habr.com/ru/post/1787594/


All Articles