Check value in list

I have a general list of values. I want to check if an identifier exists in this general list.

What is the easiest way to do this?

Example

List<someCustomObject> mylist = GetCustomObjectList(); int idToCheckFor = 12; 

I want to see if 12 exists in any of the user 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 bool true. I'm just trying to find out if there is an easy way, rather than iterating over each item in the list to see if idToCheckFor == someCustomObject.id and setting the variable to true if a match is found. I am sure there will be a better way to do this.

+4
source share
9 answers

If you are using .NET 3.5, it is easy to use LINQ for objects:

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

In addition, the loop is truly your only option.

+6
source
 Boolean b = myList.Find(obj => obj.id == 12) != null; 
+2
source

LINQ makes life easier

 mylist.Where(x => x.id == idToCheckFor).Any() 

thanks

+1
source

I think you are using the wrong data structure for this. What you need:

 Dictionary<int, someCustomObject> myDictionary = GetCustomObjectDictionary(); 

Now you can easily check if an identifier exists with fantastic performance.

 return myDictionary.ContainsKey(idToCheckFor); 
0
source
  bool found = mylist.Any(p => p.Id == idToCheckFor); 
0
source
 bool bExists = myList.Any(x=>x.id == idToCheckFor); 
0
source
 if(mylist.Any(Item => Item.Id == idToCheckFor)) { do(); } 
0
source

return myList.Exists (item => item.Id == idToCheckFor);

For linq resources you can check 101 linq sample

0
source

Use LINQ to Objects. Something like the following:

 var result = from l in mylist where l.id = 12 select l; return result != null; 
-one
source

All Articles