searching classes in an array
I have an array (Items
) which holds lots of instances of a class (Item
).
Item
has 2 properties, a Group and an ID.
there may be more than Item
in the array(Items
) that have the same Group and ID properties.
How do I "search"/get the first Item
which matche开发者_Python百科s a specified Group and/or ID
Something like:
Item.getbygroup([group])
which returns an item
EDIT: And what would let me find the second one? So start searching for a point in the array
Using LINQ:
where group and id are some variables to compare to
var item = Items.Where(x => x.Group == group || x.ID == id).First();
Use Array.Find
. From the documentation:
Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Array.
Example:
To search by Item.Group
:
Item firstItem = Array.Find(Items, Function(item as Item) item.Group = group);
To search by Item.ID
:
Item firstItem = Array.Find(Items, Function(item as Item) item.ID = ID);
Responding to your edit:
EDIT: And what would let me find the second one? So start searching for a point in the array
You could do this:
Dim matches as Item()
Dim secondItem as Item
matches = Array.FindAll(Items, Function(item as Item) item.Group = group)
If matches.Length >= 2 Then
secondItem = matches(1)
Else
'handle case where no second item
EndIf
精彩评论