C# 过滤具有特定属性的对象列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15253548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filtering a list of objects with a certain attribute
提问by proseidon
class Object
{
public int ID {get; set;}
public string description {get; set;}
}
If I have a List<Object> Objects
populated with various objects, and I want to find objects whose description is something particular, how would I do that?
如果我有一个List<Object> Objects
填充了各种对象的对象,并且我想找到描述特定的对象,我该怎么做?
find every Object in Objects whose description == "test"
采纳答案by Reed Copsey
You can use LINQ:
您可以使用 LINQ:
var results = Objects.Where(o => o.Description == "test");
On a side note, realize that Object
is a very poor choice of names for a class, and won't even compile as-is... I'd recommend choosing more appropriate names, and following standard capitalization conventions for C#.
在旁注中,意识到这Object
是一个非常糟糕的类名称选择,甚至不会按原样编译......我建议选择更合适的名称,并遵循 C# 的标准大写约定。
回答by yaens
try
尝试
foreach(Object obj in Objects)
{
if(obj.description.Contains("test"){
//Object description contains "test"
}
}
回答by Stephane Rolland
Like Reed Copsey answered LINQ
. +1.
就像里德科普西回答的那样LINQ
。+1。
My answer is still with LINQ
, but with my prefered way of writing it:
我的答案仍然是LINQ
,但使用我更喜欢的写作方式:
var results = from myobject in myobjects
where myobject.description == "test"
select myobject;
In the where parameter, you could put in any predicate (a function returning a bool).
在 where 参数中,您可以放入任何谓词(返回 bool 的函数)。
var results = from myobject in myobjects
where MyPredicate(myobject)
select myobject;