繁体   English   中英

确定集合中是否有n个任何值的实例

[英]Determine if there are n instances of any value in a collection

我有一个List<int> ,其值类似{1,2,1,5,4,4,1},但时间更长。 我想测试列表中是否有n个具有相同值的实例-任何值。 例如,如果我有一个类似bool duplicateCount(int n, IEnumerable<int> collection)的函数,请使用上面的列表:

repeatCount(4,list); //错误

repeatCount(3,list); //是,因为有3个1

过去,我会通过构建Dictionary<int, int>并计算每个成员的实例来解决此类问题。 但是,为了帮助我学习Linq,我想尝试使用该技术实施解决方案。

我在下面编写了一个使用groupby的查询,但是在获取每个组中元素的数量时遇到了麻烦。 关于如何进行此处的任何建议?

var q = from i in list group i by i into g select g.Count();

您可以使用GroupBy ,然后检查Any组的Count大于或等于该数字

public bool duplicateCount(int n, IEnumerable<int> collection)
{
    return collection.GroupBy(x => x).Any(g => g.Count() >= n)
}

如果要确定是否有任何值正好重复n次,则执行以下操作。

public bool duplicateCount(int n, IEnumerable<int> collection)
{
    return collection.GroupBy(x => x).Any(g => g.Count() == n)
}

还有查询语法,尽管我认为在这种情况下方法语法看起来更好,尤其是因为您无法将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)
}

除了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.

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