将WHERE语句添加到LINQ lambda表达式

时间:2017-08-16 21:58:40

标签: c# linq lambda

我在这里使用的两个表是这样构建的:

Users Table                             PurchaseLog Table

ID| LDAP| FNAME| LNAME|                 ID| UserID| PurchaseID | LOCATION |TIME

我正在尝试构建一个查询,让我了解每个用户以及他们拥有的购买数量。我试图填写的模型:

public class UserPurchaseCount{
    public string LDAP {get; set;}
    public int Count {get; set;}
}

我写的这个SQL查询似乎返回了正确的结果,

Select Users.LDAP, count(*) as Purchases
FROM Users
JOIN PurchaseLog ON PurchaseLog.UserId=Users.ID
WHERE Users.FName NOT LIKE '%name%'
AND PurchaseLog.CreatedDate <= 'some end date'
AND Purchase.CreatedDate >= 'some start date'
GROUP BY Users.LDAP

我吮吸lambdas,但我喜欢它们,并希望更好地了解它们。这是我到目前为止所得到的:

        var items = db.PurchaseLogs
                .Join(db.Users, usr => usr.UserId, x => x.ID, (usr, x) => new { usr, x })
                .GroupBy(y => new { y.x.LDAP})
                //.Where(i => i.CreatedDate >= startDate)
                //.Where(i => i.CreatedDate <= endDate)
                //.Where(i => i.FName.Contains("Guy1", StringComparison.CurrentCultureIgnoreCase) == false)
                .Select(g => new
                {
                    g.Key.LDAP,
                    Count = g.Count()
                })

                .ToList();

这个lambda表达式有效。当我取消注释WHERE子句时,编译器会抛出我的脸。

Error   6   'System.Linq.IGrouping<AnonymousType#2,AnonymousType#3>' does not contain a definition for 'FName'...

1 个答案:

答案 0 :(得分:2)

在申请条件之前不要分组:

var items =db.PurchaseLogs
             .Join(db.Users, usr => usr.UserId, x => x.ID, (usr, x) => new { usr, x })
             .Where(i => i.user.CreatedDate >= startDate)
             .Where(i => i.user.CreatedDate <= endDate)
             .Where(i => !i.x.FName.Contains("Guy1"))
             .GroupBy(y => new { y.x.LDAP})
             .Select(g => new
                         {
                          g.Key.LDAP,
                           Count = g.Count()
                          })

             .ToList();