检查对象列表是否包含具有特定值的属性 [英] Checking if a list of objects contains a property with a specific value
本文介绍了检查对象列表是否包含具有特定值的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有以下代码:
class SampleClass
{
public int Id {get; set;}
public int Name {get; set;}
}
List<SampleClass> myList = new List<SampleClass>();
//list is filled with objects
...
string nameToExtract = "test";
所以我的问题是我可以使用什么List函数从myList
中仅提取具有与我的nameToExtract
字符串匹配的Name属性的对象.
So my question is what List function can I use to extract from myList
only the objects that have a Name property that matches my nameToExtract
string.
如果这个问题确实很简单/很明显,我先向您道歉.
I apologize in advance if this question is really simple/obvious.
推荐答案
您可以使用返回一个IEnumerable<SampleClass>
.假设您想要过滤的List
,只需在上面调用.ToList()
.
Returns an IEnumerable<SampleClass>
. Assuming you want a filtered List
, simply call .ToList()
on the above.
顺便说一句,如果我今天在上面编写代码,鉴于Unicode字符串处理的复杂性,我将以不同的方式进行相等性检查:
By the way, if I were writing the code above today, I'd do the equality check differently, given the complexities of Unicode string handling:
var matches = myList.Where(p => String.Equals(p.Name, nameToExtract, StringComparison.CurrentCulture));
这篇关于检查对象列表是否包含具有特定值的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文