Only Add Unique Item To List

后端 未结 3 1383
攒了一身酷
攒了一身酷 2021-02-01 00:28

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

3条回答
  •  北海茫月
    2021-02-01 00:37

    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.

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

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

    public class RemoteDevice: IEquatable
    {
        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;
        }
    }
    

提交回复
热议问题