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.
You can use Any()
,
Any()
from Linq, finds whether any element in the list satisfies given condition or not, If satisfied then returntrue
if (ListA.Any(a => a.Id == stringID))
{
// Your logic goes here
}
MSDN : Enumerable.Any Method