简体   繁体   English

在C#中的数组列表中查找数组的索引

[英]Find index of an array in List of arrays in C#

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? 您如何在列表中找到{2,1}的索引?

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 : 我想要一个简洁的方法,如PaRiMaL RaJ在Check中建议的方法是否字符串数组存在于字符串列表中

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) (如果给定字符串数组的成员存在于字符串数组列表中,则上面的代码将返回true)

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));

You can use the SequenceEqual method for this. 您可以使用SequenceEqual方法。 See MSDN: https://msdn.microsoft.com/en-us/library/vstudio/bb348567(v=vs.100).aspx 请参阅MSDN: https//msdn.microsoft.com/en-us/library/vstudio/bb348567(v = vs.100) .aspx

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 })));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM