问题
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