Linq不同 – 计数
我期待在对象的示例列表上执行查询
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
我想用linq查询具有唯一用户login数的date列表。
例如:
01/01/2011 - 3 02/01/2011 - 5 03/01/2011 - 2 04/01/2011 - 1
我已经尝试了一些linq语句的testing,但没有一个给我想要的结果。 我得到的最接近的是给我不同的date,但与所有的用户数。
任何帮助将不胜感激。
logins .GroupBy(l => l.Date) .Select(g => new { Date = g.Key, Count = g.Select(l => l.Login).Distinct().Count() });
我意识到这是一个古老的问题,但我跑过去,看到了关于想要方法的语法的评论,并不能帮助自己回答…我可能有一个编码障碍。
在查询语法中,它看起来像这样…请注意, Distinct
和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() };
对于与原始方法语法(我个人更喜欢这个)相比较,在这里你去…
logins .GroupBy(l => l.Date) .Select(g => new { Date = g.Key, Count = g.Select(l => l.Login).Distinct().Count() });
可以在单个GroupBy调用中完成,
var Query = list.GroupBy( (item => item.DateTime), (key, elements) => new { key = key, count = elements .Distinct() .Count() } );
这样的事情可能吗?
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() });
解决这个问题的另一种方法是分组两次,检查样本
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();