如何在List<object>中搜索对象具有其字段值 [英] How to search for an object in List<object> having its field value
问题描述
问题是如何从具有字段值的List中获取对象
The question is how to get an object from List having its field value
我有一个名为f_objects的列表,里面充满了对象.
I have got list called f_objects filled with objects.
private List<F_object> f_objects;
我还有一个带有某些值的字符串:
i've got also a string with some value :
string name = "something";
F_object有一个返回其名称为name的字段的方法:
F_object got a method returning its field called name:
public string GetName()
{
return this.name;
}
是否有用于比较列表中的对象与此字段值的内置方法?还是我应该做一个循环并像这样比较:
Is there a built in method for compare objects in list vs this field value ? Or should i make a loop and compare like this:
foreach(F_object ob in f_objects)
{
if String.Equals(name, ob.GetName())
F_object found = ob;
}
推荐答案
在linq中有多种方法可以做到这一点.第一个是使用 .Where
.如果有更多的匹配项,这将满足您的需求
There are multiple ways of doing this in linq.
First one is to use .Where
. This would suite your needs if there can be more matches
IEnumerable<F_object> result = f_objects.Where(obj=>obj.GetName() == name);
第二个选项是,如果您只关心第一个匹配项,即使可能有多个匹配项,在这种情况下,请使用 .First
Second option is if you are only concerned about the first hit, even if there could be more than one, in that case use .First
f_object result = f_objects.First(obj=>obj.GetName() == name);
或者零击是一种可接受的情况(非例外)
or if zero hits is an accepted situation (non-exceptional)
f_object result = f_objects.FirstOrDefault(Obj=>obj.GetName() == name);
如果您一次只能点击一次,请使用 .Single
if you should only ever have one hit then use .Single
f_object result = f_objects.Single(obj=>obj.GetName() == name);
,或者如果您只有一次或零次点击,则使用 .SingleOrDefault
or if you can have only one or zero hits then use .SingleOrDefault
f_object result = f_objects.SingleOrDefault(obj=>obj.GetName() == name);
这篇关于如何在List<object>中搜索对象具有其字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!