对象内的 IEqualityComparer 字符串值
我很可能以错误的方式这样做,但是;
我有 LINQ 中的对象列表;
MyObj
string name
string somethingElse
List<MyObj> myObjects;
现在我试图查看该列表中是否有任何对象具有字符串值;
所以我有;
if (Model.myObjects.Contains("thisobject", new MyObjComparer()))
{
}
在比较器中我有;
public class MyObjComparer: IEqualityComparer<MyObj>
{
public bool Equals(string containsString, MyObj obj)
{
return obj.name == containsString;
}
}
如何使用比较器来检查对象字段中的字符串值?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个更简单的方法是这样做:
An easier method is to do this:
您可以使用 FindAll 方法,如下所示:
You can use FindAll method as follows:
相等比较器仅适用于判断同一类型的两个对象是否相等。我不知道你的用例,但你可以简单地做类似的事情吗
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