Can this LINQ Expression be converted from method syntax to query syntax?
I'm trying to convert this LINQ method expression to an equivalent query syntax:
var results1 =
logins.GroupBy(loginDate => loginDate.Date)
.Select(loginDates => new
{
Date = loginDates.Key,
Count = loginDates.Select(login => login.Name).Distinct().Count()
});
First, I came to this syntax, which does provide the same result, but isn't really the same.
var results2 =
from loginDate in logins
group loginDate by loginDate.Date
into loginDates
select new
{
Date = loginDates.Key,
Count = (from login in loginDates group login by login.Name).Count()
};
The difference is that I'm using a group by
statement here, which isn't the same as distinct (although it does provide the same result). Then I tried this:
var results3 =
from loginDate in logins
group loginDate by loginDate.Date
into loginDates
select new
{
Date = loginDates.Key,
Count = (from login in loginDates select login.Name).Distinct().Count()
};
However, this code is using quite some method syntax again.
It my last example the best you can get? Or is it possible to rewrite the query using less method syntax and more query syntax?
The logins
is initialized like this:
var logins = new[]
{
new {Name = "james", Date = new DateTime(2011, 01, 01)},
new {Name = "jamie", Date = new DateTime(2011, 01, 01)},
new {Name = "alex", Date = new DateTime(2011, 01, 01)},
new {Name = "james", Date = new DateTime(2011, 1, 1)},
new {Name = "matt", Date = new DateTime(2011, 1, 2)},
new {Name = "jamie", Date = new DateTime(2011, 1, 2)},
new {Name = "alex", Date = new DateTime(2011, 1, 2)},
new {Name = "james", Date = new DateTime(2011, 1, 2)},开发者_运维知识库
new {Name = "james", Date = new DateTime(2011, 1, 2)}
};
There isn't a query form for Distinct
(see this post for why). The query syntax with group by
is semantically equivalent, and is what I would go with if you want it in query form.
afaik, LINQ query syntax has no Distinct()
equivalent. Neither Count()
, Sum()
, etc. So you have to combine method/query syntax or use just method.
精彩评论