Determine if LINQ Enumerable contains object based on a condition? [duplicate]

血红的双手。 提交于 2019-12-12 13:41:27

问题


I have an IEnumerable<Project>

I want to know if this list has any element Project.ID == someID.

Is there a way to do that?


回答1:


Yes, you want to use the Any method (documentation).

IEnumerable<Project> projects = SomeMethodReturningProjects();
if(projects.Any(p => p.ID == someID))
{
    //Do something...
}



回答2:


You can use the Any() extension method.

var hasAny = projectList.Any(proj => proj.ID == someID);

Or, if you want to get that record, you can use FirstOrDefault():

var matchedProject = projectList.FirstOrDefault(proj => proj.ID == someID);

This will return null if it finds nothing that matches, but will pull the whole object if it does find it.




回答3:


Using

projects.Any(p => p.ID == someID)  

returns true (a boolean) if the predicate matched for any element.




回答4:


Yes, use the Any extension method:

list.Any(p => p.ID == someID);


来源:https://stackoverflow.com/questions/14883207/determine-if-linq-enumerable-contains-object-based-on-a-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!