Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for value in list

Tags:

c#

I've got a generic list of values. I want to check to see if an Id exists in that generic list.

What's the easiest way to go about this?

example

List<someCustomObject> mylist = GetCustomObjectList();

int idToCheckFor = 12;

I want to see if 12 exists in any of the custom objects in the list by checking each someCustomObject.Id = idToCheckFor

If a match is found, I'm good to go and my method will return a bool true. I'm just trying to figure out if there's an easy way instead of looping through each item in the list to see if idToCheckFor == someCustomObject.id and setting a variable to true if a match is found. I'm sure there's got to be a better way to go about this.

like image 342
PositiveGuy Avatar asked Feb 28 '23 21:02

PositiveGuy


2 Answers

If you're using .NET 3.5, this is easy using LINQ to objects:

return myList.Any(o => o.ID == idToCheckFor);

Aside from that, looping through is really your only option.

like image 132
Adam Robinson Avatar answered Mar 29 '23 11:03

Adam Robinson


Boolean b = myList.Find(obj => obj.id == 12) != null;
like image 33
Justin Swartsel Avatar answered Mar 29 '23 10:03

Justin Swartsel