Check if object with specific value exists in List

Viewed 14890

i am trying to check if a specific object exists in a List. I have ListA, which contains all the Elements, and i have a string, which may or may not belong to the id of one object in List A.

I know the following:

List<T>.Contains(T) returns true if the element exists in the List. Problem: I have to search for a specific Element.

List<T>.Find(Predicate<T>) returns an Object if it finds an element in the List which has the predicate. Problem: This gives me an object, but i want true or false.

Now i came up with this:

if (ListA.Contains(ListA.Find(a => a.Id == stringID)) ==true) ...do cool shit

is this the best solution? Seems kind of odd to me.

3 Answers

You can use Any(),

Any() from Linq, finds whether any element in list satisfies given condition or not, If satisfies then return true

if(ListA.Any(a => a.Id == stringID))
{
//Your logic goes here;

}

MSDN : Enumerable.Any Method

Using .Any is the best option: MSDN

if(ListA.Any(a => a.Id == stringID))
{
    //You have your value.
} 

Use Any for this.

if (ListA.Any(item => item.id == yourId))
{
   ...
}
Related