[英]Get properties of one object from the list of objects
I have a list of objects and then I want to find one object and display value of property with ID. 我有一个对象列表,然后我想找到一个对象并显示具有ID的属性的值。
Names name1 = new Names(){ID=1, User="John"};
Names name2 = new Names(){ID=2, User="Mike"};
Names name3 = new Names(){ID=3, User="Ben"};
This is list these objects below: 这是在下面列出这些对象:
List<Names> names;
Now I would like to return name of the User with ID equals 2. What inquiry I have to use when I have only list of objects? 现在,我想返回ID等于2的User的名称。当我只有对象列表时,必须使用什么查询?
You do it using one of First
, FirstOrDefault
, Single
or SingleOrDefault
dependng on your requirements, 您可以根据需要使用
First
, FirstOrDefault
, Single
或SingleOrDefault
之一来执行此操作,
I suspect the most appropriate is SingeOrDefault
based on the fact an ID is usually unique, so you only ever expect one single item with a specified ID
我怀疑最合适的是基于ID通常是唯一的事实,因此
SingeOrDefault
只能让您期望具有指定ID
单个项目
var item = names.SingleOrDefault(x => x.ID == 2);
if(item != null){
var name = item.Name;
}
The difference between Single
and SingleOrDefault
is that the former will thrw an error if not found, the latter will return the default value - null
in the case of an object. Single
和SingleOrDefault
之间的区别在于,如果找不到前者,它将引发错误,而后者将返回默认值-如果是对象,则返回null
。
Try this 尝试这个
Names name1 = new Names() { ID = 1, User = "John" };
Names name2 = new Names() { ID = 2, User = "Mike" };
Names name3 = new Names() { ID = 3, User = "Ben" };
List<Names> names = new List<Names>();
names.Add(name1);
names.Add(name2);
names.Add(name3);
To find object
with id=2
查找
id=2
object
Names obj = names.Where(x => x.ID == 2).FirstOrDefault();
int ID = obj.ID;
string UserName = obj.User;
If you are not aware of the LINQ and then try this 如果您不了解LINQ,请尝试此操作
Names name1 = new Names() { ID = 1, User = "John" };
Names name2 = new Names() { ID = 2, User = "Mike" };
Names name3 = new Names() { ID = 3, User = "Ben" };
List<Names> names = new List<Names>();
names.Add(name1);
names.Add(name2);
names.Add(name3);
foreach(var item in names)
{
if(item.ID == 2)
{
string strName = item.Name;
break;
}
}
// this will return a list containing all names which are against user ID for example 1,
// or an empty list if there is no user with ID 1
var allnames = names.Where(u => u.ID == 1).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.