只有加入独特的项目名单 [英] Only Add Unique Item To List

查看:120
本文介绍了只有加入独特的项目名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我添加远程设备列表,因为他们宣布自己在网络上。我只想给设备添加到列表中,如果它没有previously被添加。

的通知按照跨越异步接口监听到来使code添加设备可以在多个线程运行。我不知道我在做什么错,但没有母校什么,我尝试我结束了重复。以下是我目前有.....

 锁(_remoteDevicesLock)
{
    远端设备rDevice =(从D在_remoteDevices
                            其中,d.UUID.Trim()。等于(notifyMessage.UUID.Trim(),StringComparison.OrdinalIgnoreCase)
                            选择D).FirstOrDefault();
     如果(rDevice!= NULL)
     {
         //更新设备.....
     }
     其他
     {
         //创建一个新的远程设备
         rDevice =新的远端设备(notifyMessage.UUID);
         _remoteDevices.Add(rDevice);
     }
}
 

解决方案

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

HashSet.Add 将返回的错误时,该项目已存在(如果这甚至关系到你)。

您可以使用@pstrjds链接下面的构造函数(或这里)来定义相等运算符,否则你会需要实现远端设备 GetHash code &安培; 等于

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

解决方案

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

HashSet.Add will return false when the item already exists (if that even matters to you).

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).

这篇关于只有加入独特的项目名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆