views:

38

answers:

2

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 matches 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

+2  A: 

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
Jason
+3  A: 

Using LINQ:

where group and id are some variables to compare to

var item = Items.Where(x => x.Group == group || x.ID == id).First();
Tony
This isn't legal VB.NET.
Jason
what do you mean legal? (beside the fact it's not VB)
Jonathan
Sure it is, the syntax just needs to be converted to VB, i.e. something like (untested): `Dim item = Items.Where(Function(x) x.Group = group OrElse x.ID = id).First()`
Heinzi
@Jonathan: I mean exactly the fact that it's not legal VB.NET syntax.
Jason
@Heinzi: If it needs to be converted then your assertion ("[s]ure it is") is false.
Jason
ok, i don't understand what you mean by the whole legal thing. Is the code in Heinzi's comment correct/useable/proper/"legal"
Jonathan
btw you can do this without any addons/extensions/etc
Jonathan