I'm hoping this will be fairly simple and down to my lack of knowledge as a beginner but I'm trying to see if an array of ints with two elements is in a List.
Int[] meh = {1,2};
List<int[]> list1 = new List<int[]>();
List1.Add(meh);
Int[] meh2 = {1,2};
If(List1.Contains(meh2))
{
Console.WriteLine(“Found it”);
}
From reading around I gather that the array wont be found as it's to do with how Lists compare objects by reference and not value ... all examples Ive found have been to find a single int within an array in a List but not the array as a whole.
Im vaguely aware that List.Find() may be useful here but again I cant see how to use LINQ for matching both elements in each array in the list.
Any help or pointers to reading material greatly appreciated.
Thanks in advance.
答案 0 :(得分:3)
How about this
if(list1.Any(x => x.SequenceEqual(meh2)))
{
Console.WriteLine("Found it");
}
答案 1 :(得分:1)
You can use Enumerable.SequenceEqual
that will return -1 if the sequence is not found
example:
var myArr = new int[] { 3, 3 };
List<int[]> ListOfArrays = new List<int[]>
{
new int[] { 0, 0 },
new int[] { 2, 2 },
new int[] { 1, 1 },
new int[] { 3, 3 }
};
var index = ListOfArrays.FindIndex(l => Enumerable.SequenceEqual(myArr, l));
Console.WriteLine("here: " + index);
答案 2 :(得分:0)
Not sure what you want to achieve exactly. If list1 has an element [1, 2, 3] and you search for [1, 2], would that be a match, or do all elements have to match? Do they have to be in the same order? ...
Whatever you want to achieve exactly, you can do it with Any()
and SequenceEqual()
int[] meh = {1, 2};
int[] meh2 = {1, 5};
var list1 = new List<int[]>() {meh, meh2};
if (list1.Any(x => x.SequenceEqual(new[] {1, 5})))
{
Console.WriteLine("Found it");
}
Also see this answer. It contains an example where both arrays are sorted first (ie ignoring the order of the elements in the array)