How to find the index of a struct in an array c# [closed]

Sure, and you don’t even have to use LINQ 🙂

Array.FindIndex(yourarray, s => s.name == "John")

The return value from this method call is the first index of your array where the array element ( referred to as s ) has a name equal to John

findIndex can also take additional parameters to start searching part way through etc, see https://msdn.microsoft.com/en-us/library/03y7c6xy(v=vs.110).aspx

Edit:

I thought you’d asked for the array index, but it seems you want the related ID given the name.

No problem, just use the Array.Find method in the same way. Instead of returning you the index of the array where the found name was, it will return you the first struct with that name, and you can then get the ID from it

Array.Find(yourarray, s => s.name == "John") //returns the matching struct 

Note that if there is no matching name, you’ll get struct representing the default(T) back. You should also note that if you plan to manipulate the struct you get back, it WON’T change the values of the struct in the array (Find returns you a copy of the array entry). In that case, use FindIndex and then manipulate the array entry via something like yourarray[foundindex].name = "Jon"

Leave a Comment