C# 仅将唯一项目添加到列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13498111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:47:01  来源:igfitidea点击:

Only Add Unique Item To List

c#.netc#-4.0

提问by Oli

I'm adding remote devices to a list as they announce themselves across the network. I only want to add the device to the list if it hasn't previously been added.

我正在将远程设备添加到列表中,因为它们通过网络宣布自己。如果之前未添加设备,我只想将其添加到列表中。

The announcements are coming across an async socket listener so the code to add a device can be run on multiple threads. I'm not sure what I'm doing wrong but no mater what I try I end up with duplications. Here is what I currently have.....

公告是通过异步套接字侦听器发出的,因此添加设备的代码可以在多个线程上运行。我不确定我做错了什么,但无论我尝试什么,我最终都会重复。这是我目前拥有的......

lock (_remoteDevicesLock)
{
    RemoteDevice rDevice = (from d in _remoteDevices
                            where d.UUID.Trim().Equals(notifyMessage.UUID.Trim(), StringComparison.OrdinalIgnoreCase)
                            select d).FirstOrDefault();
     if (rDevice != null)
     {
         //Update Device.....
     }
     else
     {
         //Create A New Remote Device
         rDevice = new RemoteDevice(notifyMessage.UUID);
         _remoteDevices.Add(rDevice);
     }
}

采纳答案by Austin Salonen

If your requirements are to have no duplicates, you should be using a HashSet.

如果您的要求是没有重复项,则应该使用HashSet

HashSet.Addwill return falsewhen the item already exists (if that even matters to you).

当项目已经存在时,HashSet.Add将返回false(如果这对你很重要的话)。

You can use the constructor that @pstrjds links to below (or here) to define the equality operator or you'll need to implement the equality methods in RemoteDevice(GetHashCode& Equals).

您可以使用@pstrjds 链接到下面(或此处)的构造函数来定义相等运算符,或者您需要在RemoteDevice( GetHashCode& Equals) 中实现相等方法。

回答by Luke Eckley

Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.

就像接受的答案说 HashSet 没有订单一样。如果顺序很重要,您可以继续使用 List 并在添加之前检查它是否包含该项目。

if (_remoteDevices.Contains(rDevice))
    _remoteDevices.Add(rDevice);

Performing List.Contains() on a custom class/object requires implementing IEquatable<T>on the custom class or overriding the Equals. It's a good idea to also implement GetHashCodein the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx

在自定义类/对象上执行 List.Contains() 需要IEquatable<T>在自定义类上实现或覆盖Equals. GetHashCode在类中也实现也是一个好主意。这是根据https://msdn.microsoft.com/en-us/library/ms224763.aspx 上的文档

public class RemoteDevice: IEquatable<RemoteDevice>
{
    private readonly int id;
    public RemoteDevice(int uuid)
    {
        id = id
    }
    public int GetId
    {
        get { return id; }
    }

    // ...

    public bool Equals(RemoteDevice other)
    {
        if (this.GetId == other.GetId)
            return true;
        else
            return false;
    }
    public override int GetHashCode()
    {
        return id;
    }
}

回答by RavinderReddy Seelam

//HashSet allows only the unique values to the list
HashSet<int> uniqueList = new HashSet<int>();

var a = uniqueList.Add(1);
var b = uniqueList.Add(2);
var c = uniqueList.Add(3);
var d = uniqueList.Add(2); // should not be added to the list but will not crash the app

//Dictionary allows only the unique Keys to the list, Values can be repeated
Dictionary<int, string> dict = new Dictionary<int, string>();

dict.Add(1,"Happy");
dict.Add(2, "Smile");
dict.Add(3, "Happy");
dict.Add(2, "Sad"); // should be failed // Run time error "An item with the same key has already been added." App will crash

//Dictionary allows only the unique Keys to the list, Values can be repeated
Dictionary<string, int> dictRev = new Dictionary<string, int>();

dictRev.Add("Happy", 1);
dictRev.Add("Smile", 2);
dictRev.Add("Happy", 3); // should be failed // Run time error "An item with the same key has already been added." App will crash
dictRev.Add("Sad", 2);