Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object with specific value exists in List [duplicate]

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.

like image 795
QuestGamer7 Avatar asked Jan 01 '23 22:01

QuestGamer7


1 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

like image 75
Prasad Telkikar Avatar answered Jan 13 '23 10:01

Prasad Telkikar