Search code examples
c#liststructcontains

Check if List of Structs Contains an element


I've got struct Client and List of Clients.

struct Client
        {
            public IPEndPoint endpoint;   
            public string ClientName;
        }
List<Client> clientList = new List<Client>();

How can I check if my list contains Client with specific name? I've tried to do it like that

if(clientList.Find(Client => Client.ClientName == userNickname)

But it doesn't return bool value unfortunately.


Solution

  • You can use LINQ's Any() method:

    bool contains = clientList.Any(client => client.ClientName == userNickname);
    

    Any is easier in this case than Find() because Find() returns an instance of Client. You would need a further comparison (either to default(Client) like Jodrell suggested or again compare the names).