Determine if LINQ Enumerable contains an object based on a condition?

I have IEnumerable<Project>

I want to know if there is any item in this list Project.ID == someID

.

Is there a way to do this?

+3


source to share


4 answers


Yes, you want to use the method Any

( documentation ).



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

      

+9


source


You can use Any () extension method .

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

      

Or, if you want to get this entry, you can use FirstOrDefault () :



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

      

This will return null

if it doesn't find anything that matches, but pulls out the entire object if it finds one.

+5


source


Using

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

      

returns true (boolean) if the predicate matches any element.

+4


source


Yes, use the extension method Any

:

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

      

+3


source







All Articles