【问题标题】:Linq to SQL with Group by使用 Group by 的 Linq to SQL
【发布时间】:2010-11-15 16:32:13
【问题描述】:

我正在尝试将此 T-SQL 转换为 Linq To SQL,但无法通过聚合函数计算出组。欢迎任何帮助。

select c.ClientID, GivenName, Surname, max(a.Address), max(t.Value)
from Client c
left join ClientAddress a on c.ClientID = a.ClientID
left join ClientContact t on c.ClientID = t.ClientID
group by c.ClientID, GivenName, Surname

【问题讨论】:

    标签: c# linq-to-sql tsql


    【解决方案1】:

    要按复合键分组,通常使用匿名类型:

        var qry = from x in someSource
                  group x by new { x.ClientID, x.GivenName, x.Surname } into grp
                  select new { grp.Key, Address = grp.Max(x => x.Address),
                      Value = grp.Max(x => x.Value) };
    

    【讨论】:

      【解决方案2】:

      我想出的确切答案是

      public IQueryable<ClientSearchDTO> GetClientsDTO()
              {
                  return (from client in this.Context.Clients
                         join address in this.Context.ClientAddresses on client.ClientID equals address.ClientID
                         join contact in this.Context.ClientContacts on client.ClientID equals contact.ClientID                   
                         where contact.ContactType == "Phone"
                         group client by new { client.ClientID, client.Surname, client.GivenName } into clientGroup
                         select new ClientSearchDTO()
                          {
                              ClientID = clientGroup.Key.ClientID,
                              Surname = clientGroup.Key.Surname,
                              GivenName = clientGroup.Key.GivenName,
                              Address = clientGroup.Max(x => x.ClientAddresses.FirstOrDefault().Address),
                              PhoneNumber = clientGroup.Max(x => x.ClientContacts.FirstOrDefault().Value)
                          });
              }
      

      【讨论】:

        猜你喜欢
        • 2010-12-31
        • 2011-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-26
        • 2012-12-08
        • 1970-01-01
        相关资源
        最近更新 更多