Steve Wortham
Steve Wortham

Reputation: 22230

How do I get distinct rows along with the count of identical rows in Linq?

In SQL this would be easy for me...

SELECT browser, browser_version, page_name, COUNT(*) as cnt 
FROM traffic
GROUP BY browser, browser_version, page_name

This would return one row for each unique combination of browser, browser_version, page_name, along with the count of duplicates.

I'd like to do the same thing in Linq, but I'm not sure how to do it.

By the way, I'm not using SQL in this case because the data didn't come from SQL. It came from Windows Azure Table Storage. And I'm working with the data in-memory.

Upvotes: 1

Views: 201

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292465

var query =
    from t in traffic
    group t by new { t.browser, t.browser_version, t.page_name } into g
    select new
    {
        g.Key.browser,
        g.Key.browser_version,
        g.Key.page_name,
        Count = g.Count()
    }

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564451

You'd use a similar method:

var results = traffic.GroupBy(t => new { t.browser, t.browser_version, t.page_name });

foreach(var group in results)
{
    Console.WriteLine("{0}/{1}/{2} has {3} items.", 
            group.Key.browser, 
            group.Key.browser_version, 
            group.Key.page_name, 
            group.Count());
}

Upvotes: 1

Related Questions