Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq distinct - Count

Tags:

c#

linq

I am looking to perform a query on an example list of objects

Date     Username  01/01/2011 james 01/01/2011 jamie 01/01/2011 alex 01/01/2011 james 02/01/2011 matt 02/01/2011 jamie 02/01/2011 alex 02/01/2011 james 02/01/2011 james 02/01/2011 lucy 02/01/2011 alex 03/01/2011 james 03/01/2011 bob 03/01/2011 bob 03/01/2011 james 03/01/2011 james 04/01/2011 alex 04/01/2011 alex 04/01/2011 alex 

I want to use linq to query the list of dates with the number of unique user logins.

For example:

01/01/2011 - 3 02/01/2011 - 5 03/01/2011 - 2 04/01/2011 - 1 

I have tried as tested a number of linq statements but none of these are giving me the desired result. The closest I have got is giving me the distinct dates but with a count of all the users.

Any help would be greatly appreciated.

like image 954
Matt Seymour Avatar asked Feb 03 '11 09:02

Matt Seymour


People also ask

Where is distinct in LINQ?

It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL). IEnumerable<data type> result = numbers. Distinct(); Here is a sample code showing the implementation of C# LINQ Distinct().

How do you count in LINQ?

In LINQ, you can count the total number of elements present in the given sequence by using the Count Method. This method returns the total number of elements present in the given sequence.

What is distinct count?

Count is the total number of values. Count Distinct in the number of unique values. Count Distinct will always be equal to or less than Count. 1 Helpful. Share.


1 Answers

logins   .GroupBy(l => l.Date)   .Select(g => new   {     Date = g.Key,     Count = g.Select(l => l.Login).Distinct().Count()   }); 
like image 92
oryol Avatar answered Oct 13 '22 00:10

oryol