我有一个List,其中每个元素都是一个整数列表。我想开发LINQ来计算每个列表中==到0的整数数。
所以定义我的名单
var prisoners = new List<List<int>>(n);
for (int c = 0; c < n; c++)
{
int[] l = new int[n];
prisoners.Add(new List<int>());
prisoners[c] = l.ToList<int>();
}
所以我创建了一个包含n个整数列表的列表,全部为零 - 我感兴趣的是每个列表中的零个数,特别是该计数的最小值,直到我在列表上工作为n一开始。
我想出了
var q = (from arr in prisoners from int tally in arr
where tally == 0
group arr by arr into grp select grp.Count()).Min();
现在问题似乎是当一个列表中根本没有零时,它会离开查询,而我得不到答案为零。起初我得到答案&#39; n&#39; (当它们都为零时) - 一旦列表中没有零,我就不会得到最小零数的答案为零。
如何在列表中包含的任何列表中找到最小零数? (最终将为零)。我需要制作它以便所有列表进入分组,然后我计算有多少个零 - 但我不知道该怎么做。
实施例
int n = 3;
var prisoners = new List<List<int>>(n);
for (int c = 0; c < n; c++)
{
int[] l = new int[n];
prisoners.Add(new List<int>());
prisoners[c] = l.ToList<int>();
}
//return 3 below - that is correct at this point
var q = (from arr in prisoners from int tally in arr where tally == 0 group arr by arr into grp select grp.Count()).Min();
prisoners[1] = (new int[] { 1, 1, 1 }).ToList();
prisoners[2] = (new int[] { 1, 1, 0 }).ToList();
//so now one of the arrays has zero zeroes in it, but I get the answer 1 - zero was wanted, that is to say
//element 1 has a zero count of zero
q = (from arr in prisoners from int tally in arr where tally == 0 group arr by arr into grp select grp.Count()).Min();
答案 0 :(得分:4)
问题是,如果内部列表没有零,则过滤掉内部列表,因此您没有将0作为正确的最小值。要解决此问题,您可以执行以下操作。
var q = prisoners.Min(row => row.Count(x => x == 0));
只要prisoners
不为空,这将有效。在这种情况下,它会抛出异常。如果你想在这种情况下结果为0,你可以做以下事情。
var q = prisoners.DefaultIfEmpty().Min(row => row?.Count(x => x == 0)) ?? 0;
如果您没有C#6,则可以使用以下内容
var q = prisoners.Any() ? prisoners.Min(row => row.Count(x => x == 0)) : 0;
答案 1 :(得分:3)
您不需要分组:
var q = prisoners.Min(arr=>arr.Count(tally=>tally==0));
作为查询表达式:
var q = (from arr in prisoners select arr.Count(tally=>tally==0)).Min();