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.
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.
Boolean b = myList.Find(obj => obj.id == 12) != null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With