Reputation: 27
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.
Upvotes: 1
Views: 94
Reputation: 1391
You can use Linq:
var index = -1;
var foundSubState = States.FirstOrDefault(x => {
index++;
return x.SequenceEqual(SubState);
});
var res = foundSubState != default(Array) ? index : -1;
Upvotes: 0
Reputation: 726559
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.
Upvotes: 0
Reputation: 54887
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));
Upvotes: 1