6

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.

QuestGamer7
  • 133
  • 1
  • 1
  • 8
  • I did, as a matter of fact i did quite some heavy searching (I always do) but all i could find was Find(), FindIndexOf, Contains etc. Thats how i created the Code i showed. – QuestGamer7 Jun 05 '19 at 11:44
  • Out of curiosity I tried: https://www.google.com/search?q=c%23+list+find+bool – Rand Random Jun 05 '19 at 11:59
  • I searched for stuff like "c# list check if object exists" and didnt find anything. Maybe i would have if i had gone to page 2 or 3 of the results but seriously, who does shit like that – QuestGamer7 Jun 05 '19 at 16:33

3 Answers3

11

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

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
2

Using .Any is the best option: MSDN

if(ListA.Any(a => a.Id == stringID))
{
    //You have your value.
} 
Mikev
  • 2,012
  • 1
  • 15
  • 27
1

Use Any for this.

if (ListA.Any(item => item.id == yourId))
{
   ...
}
Tomas Chabada
  • 2,869
  • 1
  • 17
  • 18