C# 使用循环检查数组中的最后两个数字是否都存在于2D数组中
我有两个数组,一个是单数数组,另一个是二维数组C# 使用循环检查数组中的最后两个数字是否都存在于2D数组中,c#,arrays,C#,Arrays,我有两个数组,一个是单数数组,另一个是二维数组 int[][] array1 = { new int [] {1, 22, 3, 44, 5, 66}, new int [] {11, 22, 33, 44, 55, 66}, new int [] {1, 2, 3, 4, 5, 6}, }; int[] array2 = new int[] {1, 2, 3, 5, 66} 我需要创建一个循环,在数组1中搜索数组2中的最后两位数字,这样它将返回数组1同时包含5和6
int[][] array1 = {
new int [] {1, 22, 3, 44, 5, 66},
new int [] {11, 22, 33, 44, 55, 66},
new int [] {1, 2, 3, 4, 5, 6},
};
int[] array2 = new int[] {1, 2, 3, 5, 66}
我需要创建一个循环,在数组1中搜索数组2中的最后两位数字,这样它将返回数组1同时包含5和66的次数,即1,因为其他两个仅包含每个数字中的1
我已经成功地编写了一个函数,返回数组2作为一个整体存在于数组1中的次数,这个新函数实际上是对它的一种改进
for (int a = 0; a < array1[i].Length; a++)
{
for (int b = 0; b < array2.Length; b++)
{
if (array2[c] == array1[a][b])
count++;
temp[b] = array1[a][b];
}
}
for(int a=0;a
我觉得搜索最后两个数字所需要的只是对这个函数的一个小小的更改,我尝试添加另一个循环,但也没有成功。我该怎么做呢?由于我还在学习基础知识,所以我使用循环和不包含是有原因的。有一件事尚不清楚,这两个数字出现在2D数组中的哪个位置重要吗? 如果情况并非如此,则可以使用默认相等比较器来比较值,从而生成两个序列的集合交集:
var result = array1.Count(x => x.Intersect(array2.Reverse().Take(2)).Count() == 2);
如果您注意了,我们使用这一行来获取array1
的最后两个元素:
array1.Reverse().Take(2);
附加:
如果要查找2D数组中数组的最后两个元素是否等于数组1的最后两个元素,则可以尝试LINQ解决方案:
var result = array1.Count(x=> x.Reverse().Take(2).SequenceEqual(array2.Reverse().Take(2)));
使用的扩展方法说明:反转序列中元素的顺序。
从序列开始返回指定数量的连续元素。
通过使用元素类型的默认相等比较器来比较元素,确定两个序列是否相等 获取两个数组的最后两个元素后,我们将使用
SequenceEqual()
确定两个数组是否相等
var res = array1.Where((x) => (x.Contains(array2.Last()) && x.Contains(array2[array2.Length - 2]))).Count();
解释:
- 阵列1.Where获取阵列1的每个子阵列并过滤 满足某个条件。
- 条件是 array1包含array2的最后一个和下一个元素。
-
Count()方法返回满足
条件
using System;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
[STAThread]
private static void Main()
{
int[][] array1 =
{
new [] {1, 22, 3, 44, 5, 66},
new [] {11, 22, 33, 44, 55, 66},
new [] {1, 2, 3, 4, 5, 6},
new [] {1, 66, 3, 4, 5, 6} // This one has the target items out of order.
};
int[] array2 = {1, 2, 3, 5, 66};
// Extract the targets like this; it avoids making a copy
// of array2 which occurs if you use IEnumerable.Reverse().
int[] targets = {array2[array2.Length - 2], array2[array2.Length - 1]};
// Count the number of times that each subarray in array1 includes
// all the items in targets:
int count = array1.Count(array => array.Intersect(targets).Count() == targets.Length);
Console.WriteLine(count);
}
}
}
这两个数字出现在2D数组中的哪个位置(例如,仅在末尾)或可以出现在任何位置都有关系吗?@MatthewWatson一点也不重要,例如数组(5、74、73、92、48、66)仍然可以计数++,我只是想寻找两个数字都不按特定顺序存在的数组。有点像彩票中的supp数字。@RobertPaulson那么,你可以试试我的答案。@RobertPaulson我在答案中添加了完整的代码。在loop@RobertPaulson您不能将其包括在循环中。这行就够了。别忘了使用Sytem.Linq@RobertPaulson在我的答案中包含
,该答案提供了指向Fiddle的链接。通常避免只使用代码的答案。考虑添加<代码>描述< /代码>,这有助于解释代码。谢谢