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); } }
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).
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.
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.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With