简体   繁体   English

C#检查List是否包含具有相同值的自定义对象

[英]C# Check if List contains a custom object with the same value

I have a custom object (the properties must be strings): 我有一个自定义对象(属性必须是字符串):

public class Nemesis
{
    public String Dex_ID;
    public String Value;
}

I have a certain function, which creates new instances of that object, adds values to them and then adds them to this List: 我有一个特定的函数,它创建该对象的新实例,向它们添加值,然后将它们添加到此List:

private List<Nemesis> _nemesisList;
public List<Nemesis> NemesisList
{
    get { return _nemesisList; }
    set { _nemesisList = value; }
}

Normally, I'd use this to check for existing things: 通常,我会用它来检查现有的东西:

if (!NemesisList.Contains(nemesis))
{
    NemesisList.Add(nemesis);
}

But this time I want to check if my List already contains a nemesis with the same nemesis.Dex_ID . 但是这一次我想检查我的List是否已经包含一个具有相同nemesis.Dex_ID克星 How do I do that? 我怎么做?

If you only want to to check against the the ID field and ignore others then you can do : 如果您只想检查ID字段并忽略其他字段,那么您可以执行以下操作:

if(!NemesisList.Any(n=> n.Dex_ID == nemesis.Dex_ID))

otherwise if you want to perform comparison for all the fields then you can override Equals and GetHashCode . 否则,如果要对所有字段执行比较,则可以覆盖EqualsGetHashCode

See: Correct way to override Equals() and GetHashCode() 请参阅: 重写Equals()和GetHashCode()的正确方法

Using LINQ: 使用LINQ:

if (!NemesisList.Any(n => n.Dex_ID == nemesis.Dex_ID)) // ...

OR 要么

if (!NemesisList.Select(n => n.Dex_ID).Contains(nemesis.Dex_ID)) // ...

The better solution is probably to create a dictionary though. 更好的解决方案可能是创建一个字典。 They are built for quick lookups based on some key value. 它们是为基于某些键值的快速查找而构建的。

if (!NemesisDict.ContainsKey(nemesis.Dex_ID)) // ...

Linq是你的朋友:

if (!myList.Any(x => x.Dex_ID == nemesis.Dex_ID)) myList.Add(nemesis)

尝试使用以下LINQ:

var exists = NemesisList.Any(n=>n.Dex_Id==id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM