Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only Add Unique Item To List

Tags:

c#

.net

c#-4.0

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);      } } 
like image 700
Oli Avatar asked Nov 21 '12 16:11

Oli


People also ask

How do I add unique elements to a list?

In order to find the unique elements, we can apply a Python for loop along with list. append() function to achieve the same. At first, we create a new (empty) list i.e res_list. After this, using a for loop we check for the presence of a particular element in the new list created (res_list).

Which of the following has only unique values?

A set only contains unique values. In this approach we convert the list to a set and then convert the set back to a list which holds all the unique elements.

How do I get a list of unique items in Excel?

In Excel, there are several ways to filter for unique values—or remove duplicate values: To filter for unique values, click Data > Sort & Filter > Advanced. To remove duplicate values, click Data > Data Tools > Remove Duplicates.


1 Answers

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

like image 101
Austin Salonen Avatar answered Sep 19 '22 02:09

Austin Salonen