Justin R.
Justin R.

Reputation: 24021

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. I would like to test if there are n instances of the same value - any value - in the list. For example, if I had a function like bool duplicateCount(int n, IEnumerable<int> collection), using the above list:

duplicateCount(4, list); // false

duplicateCount(3, list); // true, as there are 3x '1's

In the past I would resolve a problem like this by building a Dictionary<int, int> and count the instances of each member. However, in order to help me learn Linq, I would like to try to implement a solution with that technology.

I have written a query that uses groupby, below, but I'm having trouble getting the number of elements in each group. Any advice on how to proceed here?

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

Upvotes: 0

Views: 105

Answers (2)

juharr
juharr

Reputation: 32266

You can do that with a GroupBy and then checking if Any group has a Count greater than or equal to the number

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.

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.

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)
}

Upvotes: 4

Rohit
Rohit

Reputation: 10236

something other than lambda expressions

 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();

Upvotes: 0

Related Questions