访问列表< Class>中的类的属性. [英] Accessing Property of Class in List<Class>
问题描述
我看到了很多类似的问题,但是没有一个直接的答案.我有一个 List< ClientEntry>
.我想访问ClientEntry中的属性.我的代码如下:
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;
}
}
}
}
稍后:
private List<ClientEntry> clientList;
然后我将一堆ClientEntry添加到列表中.
I then add a bunch of ClientEntry's to the List.
如何访问clientList中项目的ClientName和ClientEmail属性?另外,如何检查列表中是否存在某些ClientName或ClientEmail属性?使用对象列表甚至可能吗?我知道dict可能会更好,但是我想看看是否可以使用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.
推荐答案
您可以使用Linq使用 Any()
You can use Linq to look for values inside of a list using Any()
例如.
bool emailExists = clientList.Any(x=>x.ClientEmail == <email>);
要访问值,可以使用索引访问器(如果知道),循环收集或使用 Where()
进行搜索:
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
或
foreach (var client in clientList)
{
var email = client.ClientEmail
}
或
var email = clientList.Where(x=>x.ClientName == <clientName>).FirstOrDefault();
这篇关于访问列表< Class>中的类的属性.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!