1

I have a two dimensional array namely States. I create a one dimensional array, say SubState. Then I change SubState. I want to find new SubState in States and get the index. As an example:

int[][] States = new int[3][] { new int[] { 3, 3, 4 }, new int[] { 2, 5, 1 }, new int[] { 2, 3, 4 } };
int[] SubState = new int[States[0].Length];
States[0].CopyTo(SubState, 0);
SubState[0] -= 1;

I want to find the index of new SubState in State, which will be 2 in the example. Thanks.

4
  • 1
    What is the problem that you're trying to solve? Your question doesn't make much sense and this approach doesn't seem very flexible or maintainable. Commented Aug 7, 2015 at 16:55
  • 3
    FYI that's not a 2 dimensional array, that's a jagged array. A 2 dimensional array would be defined as int[3,3]. Commented Aug 7, 2015 at 17:00
  • I have a two dimensional array which contains some one dimensional arrays. Some of these arrays differ each other in one element. For example [3,3,4] differs with [2,3,4] & [3,2,4] &[3,3,3] in one element by 1. I want to find indices of these three arrays in the the main two dimensional array. Commented Aug 7, 2015 at 17:05
  • Thank you very much. As a beginner, I have made a lot of mistakes :). Commented Aug 7, 2015 at 17:13

3 Answers 3

1

You're looking for SequenceEqual:

int index = -1;
for (int i = 0; i < States.Length; i++)
    if (States[i].SequenceEqual(SubState))
    {
        index = i;
        break;
    }

If you define a LINQ FindIndex operator, you can express it more concisely using:

int index = States.FindIndex(s => s.SequenceEqual(SubState));
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. That really helped. It would be appreciated if you tell me how to define a LINQ FindIndex operator too. Thanks.
@M.Mohebbi: You can copy the implementation from the linked answer: stackoverflow.com/a/2471631/1149773
0

You can use SequenceEqual method inside a LINQ query, like this:

var nextStateIndex = States
    .Select((a, i) => new {Index = i, Array = a})
    .FirstOrDefault(p => p.Array.SequenceEqual(SubState))
    ?.Index;
if (nextStateIndex.HasValue) {
    ...
}

Note: this code uses the new ?. operator. If you are targeting C# version that does not have support for this operator, store FirstOrDefault result for an explicit null checking.

Comments

0

You can use Linq:

  var index = -1;

  var foundSubState = States.FirstOrDefault(x => {
    index++;
    return x.SequenceEqual(SubState);
  });

  var res = foundSubState != default(Array) ? index : -1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.