Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Property of Class in List<Class>

Tags:

c#

I see a lot of similar questions but none with a direct answer. I have a List<ClientEntry>. I want to access properties in ClientEntry. My code looks like this:

class ClientEntry
{
    private string _clientName;
    private string _clientEmail;

    public void ClientEntry(string name, string email)
    {
        this._clientName = name;
        this._clientEmail = email;
    }

    public string ClientName
    {
        get
        {
            return _clientName;

        }
        set
        {
            _clientName = value;
        }
    }

    public string ClientEmail
    {
        get
        {
            return _clientEmail;
        }
        set
        {
            RegexUtilities Validator = new RegexUtilities();
            if (Validator.IsValidEmail(value))
            {
                _clientEmail = value;
            }
        }
    }
}

Later:

private List<ClientEntry> clientList;

I then add a bunch of ClientEntry's to the List.

How can I access the ClientName and ClientEmail properties for items in clientList? Also, how can I check for the existance of a certain ClientName or ClientEmail property within the List? Is this even possible with a list of objects? I know a dict would probably serve better, but I wanted to see if this could be done with a List and a class with properties.

like image 713
ss7 Avatar asked May 26 '15 02:05

ss7


Video Answer


2 Answers

You can use Linq to look for values inside of a list using Any()

Eg.

bool emailExists = clientList.Any(x=>x.ClientEmail == <email>);

To access values, you can use a index accessor if you know it, loop the collection, or use Where() to search it:

var email = clientList[index].ClientEmail

or

foreach (var client in clientList)
{
    var email = client.ClientEmail
}

or

var email = clientList.Where(x=>x.ClientName == <clientName>).FirstOrDefault();
like image 90
Steve Avatar answered Sep 27 '22 18:09

Steve


you can explore your list as below

 foreach (ClientEntry client in clientList)
  {
    //client.ClientName
    //client.ClientEmail
  }

to find a particular record you can search it as

clientList.Where(p=> p.ClientEmail == "[email protected]").FirstOrDefault();
like image 43
Muhammad Faisal Avatar answered Sep 27 '22 19:09

Muhammad Faisal