98

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

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

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);
     }
}
4

3 回答 3

169

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

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

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

于 2012-11-21T16:55:05.233 回答
26
//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);
于 2016-11-07T13:51:22.167 回答
19

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

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

在自定义类/对象上执行 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;
    }
}
于 2016-03-16T21:17:16.550 回答