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;
LINQ makes life easier
mylist.Where(x => x.id == idToCheckFor).Any()
Thanks
bool found = mylist.Any(p => p.Id == idToCheckFor);
bool bExists = myList.Any(x=>x.id == idToCheckFor);
if(mylist.Any(Item => Item.Id == idToCheckFor))
{
do();
}
I think you are using the wrong data structure for this. What you need is:
Dictionary<int, someCustomObject> myDictionary = GetCustomObjectDictionary();
Now you can easily check if the ID exists with fantastic performance.
return myDictionary.ContainsKey(idToCheckFor);
return myList.Exists(item => item.Id == idToCheckFor);
For linq resources you can check 101 linq samples
Use LINQ to Objects. Something like the following:
var result = from l in mylist
where l.id = 12
select l;
return result != null;
精彩评论