3

I want to find index of a character in char Array. I wrote below code, but I want to use some library function/ LINQ to find the index rather than manually looping through it. Is there any smarter way/ concise way I can achieve it.

Attempt:

    var index = -1;
    char[] x = { 'A', 'B', 'C', 'D' , 'E'};

    for(int t = 0; t< x.Length; t++)
    {
        if (x[t] == 'E')
            index = t;
    }

    Console.WriteLine($"Index is:  {index}");
0

3 Answers 3

11

For this example, you could use Array.IndexOf.

char[] x = { 'A', 'B', 'C', 'D', 'E' };

Console.WriteLine($"Index is:  {Array.IndexOf(x, 'E')}");
Sign up to request clarification or add additional context in comments.

Comments

1

This is with LINQ :

char[] x = { 'A', 'B', 'C', 'D', 'E' };
var index = x.Select((c, i) => new {c, i}).SingleOrDefault(c => c.Equals('D')).i

with array class:

var index = Array.FindIndex(x, c=> c.Equals('E'));

4 Comments

Underneath the hood, it loops through the array. I think the OP wants an efficient algorithm to do this.
@ZackISSOIR: It's not like it's an indexed array. Finding an item in an ordinary array is O(n).
@ZackISSOIR: How would you find that without looping through the array. As Robert Harvey points out, just about any useful solution will be an O(n) problem
You're right @RobertHarvey :)
0

Use System.Linq FindIndex

char[] x = { 'A', 'B', 'C', 'D' , 'E'};
int index = x.ToList().FindIndex(c => c == 'E');

2 Comments

This requires that you enumerate the collection twice.
Well its a solution and since the array is not that big it should not be a problem :) you think about performance issue when you have an array that are over at least 1000 :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.