7

If you had a List of arrays like:

List<int[]> ListOfArrays = new List<int[]>();
ListOfArrays.Add(new int[] { 1, 1 });
ListOfArrays.Add(new int[] { 2, 1 });

How would you find the index of { 2, 1} in the List?

I do not want to use an iteration loop. I would like a concise method like the one suggested by PaRiMaL RaJ in Check if string array exists in list of string:

list.Select(ar2 => arr.All(ar2.Contains)).FirstOrDefault();

(the above code will return true if members of a given string array exist in a list of string arrays)

4
  • 1
    The only way to avoid an iteration loop will be a dictionary respectively a hash-lookup-table. Commented Oct 31, 2015 at 12:19
  • @xXliolauXx By iteration I think he means LINQ instead of a hand written loop. Commented Oct 31, 2015 at 12:23
  • Does the order of the internal array matter? Commented Oct 31, 2015 at 12:25
  • @Yuval ah I see... I thought it was the performance he wanted to keep high... And I thought of LinQ using loops too... Commented Oct 31, 2015 at 12:35

3 Answers 3

9
var myArr = new int[] { 2, 1 };
List<int[]> ListOfArrays = new List<int[]>();
ListOfArrays.Add(new int[] { 1, 1 });
ListOfArrays.Add(new int[] { 4, 1 });
ListOfArrays.Add(new int[] { 1, 1 });
ListOfArrays.Add(new int[] { 2, 1 });

int index = ListOfArrays.FindIndex(l => Enumerable.SequenceEqual(myArr, l));
Sign up to request clarification or add additional context in comments.

2 Comments

You can shorten it a bit: ListOfArrays.FindIndex(l => l.SequenceEqual(myArr));
ListOfArrays.FindIndex(myArr.SequenceEqual); should also work
1

You can use the SequenceEqual method for this. See MSDN: https://msdn.microsoft.com/en-us/library/vstudio/bb348567(v=vs.100).aspx

1 Comment

Thanks Markus, I would have to use a foreach loop over the List and check each member. There should be a more clever way.. :/
1

You can try this:

List<int[]> ListOfArrays = new List<int[]>();
ListOfArrays.Add(new int[] { 1, 1 });
ListOfArrays.Add(new int[] { 2, 1 });
var chk = ListOfArrays.FindIndex(e => (e.SequenceEqual(new int[] { 2, 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.