[英]Determine if there are n instances of any value in a collection
I have a List<int>
with values like { 1, 2, 1, 5, 4, 1 }, only much longer. 我有一个
List<int>
,其值类似{1,2,1,5,4,4,1},但时间更长。 I would like to test if there are n instances of the same value - any value - in the list. 我想测试列表中是否有n个具有相同值的实例-任何值。 For example, if I had a function like
bool duplicateCount(int n, IEnumerable<int> collection)
, using the above list: 例如,如果我有一个类似
bool duplicateCount(int n, IEnumerable<int> collection)
的函数,请使用上面的列表:
duplicateCount(4, list);
repeatCount(4,list); // false
//错误
duplicateCount(3, list);
repeatCount(3,list); // true, as there are 3x '1's
//是,因为有3个1
In the past I would resolve a problem like this by building a Dictionary<int, int>
and count the instances of each member. 过去,我会通过构建
Dictionary<int, int>
并计算每个成员的实例来解决此类问题。 However, in order to help me learn Linq, I would like to try to implement a solution with that technology. 但是,为了帮助我学习Linq,我想尝试使用该技术实施解决方案。
I have written a query that uses groupby, below, but I'm having trouble getting the number of elements in each group. 我在下面编写了一个使用groupby的查询,但是在获取每个组中元素的数量时遇到了麻烦。 Any advice on how to proceed here?
关于如何进行此处的任何建议?
var q = from i in list group i by i into g select g.Count();
You can do that with a GroupBy
and then checking if Any
group has a Count
greater than or equal to the number 您可以使用
GroupBy
,然后检查Any
组的Count
大于或等于该数字
public bool duplicateCount(int n, IEnumerable<int> collection)
{
return collection.GroupBy(x => x).Any(g => g.Count() >= n)
}
Or the following if you want to determine if there is any value repeated exactly n times. 如果要确定是否有任何值正好重复n次,则执行以下操作。
public bool duplicateCount(int n, IEnumerable<int> collection)
{
return collection.GroupBy(x => x).Any(g => g.Count() == n)
}
There is also query syntax, though I think in this case method syntax looks better, especially since you cannot translate Any
to query syntax. 还有查询语法,尽管我认为在这种情况下方法语法看起来更好,尤其是因为您无法将
Any
转换为查询语法。
public bool duplicateCount(int n, IEnumerable<int> collection)
{
return (from item in collection
group by item into grp
select grp.Count()).Any(count => count == n)
}
something other than lambda expressions 除了lambda表达式
List<int> list = new List<int>() { 1, 2, 3, 3, 3, 4, 4, 4, 4,2,2,2, 2, 2, 2, 5, 5, 5, 5 };
var q = (from i in list
where i == 2
select i).Count();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.