80

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.

1
  • 9
    Please add those LINQ statements you tried - then we can see why they went wrong. Commented Feb 3, 2011 at 9:46

7 Answers 7

149
logins
  .GroupBy(l => l.Date)
  .Select(g => new
  {
    Date = g.Key,
    Count = g.Select(l => l.Login).Distinct().Count()
  });
9
  • 6
    I'm new to Linq and I'm wondering how you would write this in Linq query syntax in stead of Linq method syntax.
    – comecme
    Commented Feb 3, 2011 at 11:26
  • 1
    @comecme I realize you left this comment ages ago but check out my translation to method syntax below.
    – Kevin
    Commented Dec 18, 2014 at 21:33
  • 4
    Im afraid your code will always return Count=1, thats because you added the Disctinct() and will make the to count one element. If you remove that, you will have the quantity of elements. Hope this helps!!! ;) Commented Nov 24, 2015 at 14:40
  • For example, for some source array [1, 1, 2]: distinct count = 2, count = 3. Obviously, nothing of them isn't equal to 1. We do really need distinct there if we need to calculate unique logins. Using just Count will give wrong number (total logins, not unique).
    – oryol
    Commented Nov 24, 2015 at 17:10
  • 1
    Without distinct it gives total login session count for this date. Even if they were for the same user. With distinct - it gives count of users who logged in in each date. Probably, you have slightly different data structure / target number that topic starter
    – oryol
    Commented Aug 4, 2019 at 17:19
21

I realize this is an ancient question but I ran across it and saw the comment about wanting method syntax and couldn't help myself to answer it... I may have a coding disorder.

In query syntax it looks like this... note that there is no query syntax for Distinct and Count

from l in logins
group l by l.Date into g
select new
{
    Date = g.Key,
    Count = (from l in g select l.Login).Distinct().Count() 
};

For a side by side comparison to the original method syntax (which personally I like better) here you go...

logins
  .GroupBy(l => l.Date)
  .Select(g => new
  {
    Date = g.Key,
    Count = g.Select(l => l.Login).Distinct().Count()
  });
1
  • 1
    Thank you for taking the time to answer my comment.
    – comecme
    Commented Dec 19, 2014 at 7:18
14

Can be done within single GroupBy call,

  var Query = list.GroupBy(
                 (item => item.DateTime),
                 (key, elements) => new  { 
                                          key = key,
                                          count = elements
                                                  .Distinct()
                                                  .Count()
                                         }
                 );
1
  • it will give wrong result (total session count per day, not unique usernames per day)
    – oryol
    Commented Jul 17, 2020 at 10:12
5

Something like this maybe?

var list = new List<MyClass>(new[] {
        new MyClass { Date = DateTime.Parse("01/01/2011"), Username = "james" },
        new MyClass { Date = DateTime.Parse("01/01/2011"), Username = "james" },
        new MyClass { Date = DateTime.Parse("01/01/2011"), Username = "alex" },
        new MyClass { Date = DateTime.Parse("01/01/2011"), Username = "james" },
        new MyClass { Date = DateTime.Parse("02/01/2011"), Username = "matt" },
        new MyClass { Date = DateTime.Parse("02/01/2011"), Username = "jamie" },
        new MyClass { Date = DateTime.Parse("02/01/2011"), Username = "alex" },
        new MyClass { Date = DateTime.Parse("02/01/2011"), Username = "james" },
        new MyClass { Date = DateTime.Parse("02/01/2011"), Username = "james" },
        new MyClass { Date = DateTime.Parse("02/01/2011"), Username = "lucy" },
        new MyClass { Date = DateTime.Parse("02/01/2011"), Username = "alex" },
        new MyClass { Date = DateTime.Parse("03/01/2011"), Username = "james" },
        new MyClass { Date = DateTime.Parse("03/01/2011"), Username = "bob" },
        new MyClass { Date = DateTime.Parse("03/01/2011"), Username = "bob" },
        new MyClass { Date = DateTime.Parse("03/01/2011"), Username = "james" },
        new MyClass { Date = DateTime.Parse("03/01/2011"), Username = "james" },
        new MyClass { Date = DateTime.Parse("04/01/2011"), Username = "alex" },
        new MyClass { Date = DateTime.Parse("04/01/2011"), Username = "alex" },
        new MyClass { Date = DateTime.Parse("04/01/2011"), Username = "alex" }
    });

list.GroupBy(l => l.Date, l => l.Username)
    .Select(g => new { 
                Date = g.Key, 
                Count = g.Distinct().Count() 
            });
3
  • Ahh dam it I was so clost, thank you I will look into implementing this shortly. Thanks for the quick response. Commented Feb 3, 2011 at 9:57
  • @aspect - actually this gives you the date with the associated number of unique user logins, from your question do you want to group the dates with the same number of unique user logins as well? if that's what you want, then just add another group by after the select by the count and you're there! Commented Feb 3, 2011 at 10:00
  • This seems to be the best solution we have! Initially I was grouping twice, but didn't really like having to do this. This is so straightforward in SQL, but the best way in LINQ isn't so obvious. For everyone's benefit: If you're going to write dates as strings in code, you should use ISO format. This makes sure the interpretation doesn't depend on locale.
    – Stewart
    Commented Oct 25, 2021 at 15:16
1

Another way to solve this is to group twice, check the sample

          var dist = listLogins.GroupBy(d => d.date + d.Username)
              .Select(x => x.First())
              .GroupBy(d => d.date).Select(y => new { date = y.Key, count = y.Count() }).ToList();
0

I don't think there is need of Distinct count in Oryol's answer. The groupup automatically picks distinct keys and it can be accessed as g.key

logins
  .GroupBy(l => l.Date)
  .Select(g => new
  {
    Date = g.Key,
    Count = g.Select(l => l.Login).Count()
  });
1
  • I can't see that this would work. Your code groups only by Date, not by Login. Without Distinct, it would surely count the total number of logins each day, not the number of distinct users who logged in each day?
    – Stewart
    Commented Oct 25, 2021 at 15:07
0

If you really want to avoid the Distinct method...

from login in logins
group login by login.Date into dateGroup
select new { 
     Date = dateGroup.Key, 
     UniqueLogins = (from login in dateGroup
                     group login by login.Name into uniqueNames
                     select uniqueNames).Count()
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.