C# code to find array index of a value using LINQ


C# code to find the array index of a value using LINQ

If you want to find the array index of value from the list of string, you can use the following code.

Suppose you have an array of string with name “parameterList“.

Here is the C# code

string[] parameterList= new string[] {"param1", "param2", "param3", "param4", "param5", "param6", "param7", "param8", "param9", "param10"}

Now create a function to return the array index of a value that we pass as an argument.

int GetParameterIndex(String value)
            var result =parameterList.Select((s, i) => new { Pos = i, Str = s }).Where(o => o.Str.Equals(value, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                return result.Pos;
            return -1;

Please note that: String.Equals(string1,string2, StringComparison.OrdinalIgnoreCase) used for case insensitive string comparison. You can also use Simply String.Equals(string1,string2) if you want to case sensitive string comparison. Refer here for Best Practices for Using Strings in .NET.

Now call GetParameterIndex() function:

var index=GetParameterIndex("param3");

Here variable index returns the index of param3 from the parameterList array.


How useful was this post?

Click on a star to rate it!

Average rating 3 / 5. Vote count: 2

No votes so far! Be the first to rate this post.

As you found this post useful...

Share this post on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?