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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
M. Mohebbi
  • 27
  • 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. – xxbbcc Aug 07 '15 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]`. – juharr Aug 07 '15 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. – M. Mohebbi Aug 07 '15 at 17:05
  • Thank you very much. As a beginner, I have made a lot of mistakes :). – M. Mohebbi Aug 07 '15 at 17:13

3 Answers3

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));
Community
  • 1
  • 1
Douglas
  • 53,759
  • 13
  • 140
  • 188
  • 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 Aug 07 '15 at 17:15
  • @M.Mohebbi: You can copy the implementation from the linked answer: http://stackoverflow.com/a/2471631/1149773 – Douglas Aug 07 '15 at 18:01
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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
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;
HashPsi
  • 1,391
  • 2
  • 12
  • 22