Access to the class property in the <Class> list

I see many similar questions, but with no direct answers. I have a List<ClientEntry> . I want to access properties in ClientEntry. My code is as follows:

 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; } } } } 

Further:

 private List<ClientEntry> clientList; 

Then I add the ClientEntry bunch to the list.

How can I access the ClientName and ClientEmail properties for items in the clientList? Also, how can I check for a specific ClientName or ClientEmail property in the list? Is this possible with a list of objects? I know that a dict will probably work better, but I wanted to see if this could be done with a list and a class with properties.

+6
source share
4 answers

You can use Linq to find values ​​inside a list using Any()

Eg.

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

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

 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(); 
+6
source

To access a specific item in a list, you enter an index / using foreach

 string name = clientList[index].ClientName; foreach(var client in clientList) { name = client.ClientName; // access the item one by one } 

To check for the existence of a specific property value, use linq

 bool isExist = clientList.Any(i => i.ClientName == "John"); 
+4
source

you can examine your list below

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

to find a specific entry that you can find in it as

 clientList.Where(p=> p.ClientEmail == " [email protected] ").FirstOrDefault(); 
+4
source

Use Extension Methods !

Something like this, you can easily write unit test for the extension class, and also just read it.

 public static class ClientEntriesExtension { public static bool ExistEmail(this IEnumerable<ClientEntry> entries, string targetEmail) { return entries.Any(x=>x.ClientEmail == targetEmail); } } bool exist = clientList.ExistEmail(targetEmail) 
+2
source

Source: https://habr.com/ru/post/987895/


All Articles