Totallama
Totallama

Reputation: 448

C# - Finding key in an array by the value of its complex structure

is there a method in C# to find the key of the item in an array by its "subvalue"? Some hypothetical function "findKeyofCorrespondingItem()"?

struct Items
{
 public string itemId;
 public string itemName;
}

 int len = 18;
 Items[] items = new Items[len];

items[0].itemId = "684656"; 
items[1].itemId = "411666"; 
items[2].itemId = "125487"; 
items[3].itemId = "756562"; 
// ...
items[17].itemId = "256569"; 

int key = findKeyofCorrespondingItem(items,itemId,"125487"); // returns 2

Upvotes: 0

Views: 44

Answers (2)

Vivek Nuna
Vivek Nuna

Reputation: 1

public static int findKeyofCorrespondingItem(Items[] items, string searchValue)
    {
        for (int i = 0; i < items.Length; i++)
        {
            if (items[i].itemId == searchValue)
            {
                return i;
            }
        }

        return -1;
    }

You can run a loop and check if itemId equal to the value you are searching for. Return -1 if no item matches with value.

Solution with Linq:

public static int findKeyofCorrespondingItem(Items[] items, string searchValue)
{
    return Array.FindIndex(items, (e) => e.itemId == searchValue);
}

Upvotes: 0

smibe
smibe

Reputation: 159

You can use Array.FindIndex. See https://msdn.microsoft.com/en-us/library/03y7c6xy(v=vs.110).aspx

using System.Linq
...
Array.FindIndex(items, (e) => e.itemId == "125487"));

Upvotes: 1

Related Questions