C# 如何使用linq to sql从组中选择值

C# 如何使用linq to sql从组中选择值,c#,sql-server,linq,sql-to-linq-conversion,C#,Sql Server,Linq,Sql To Linq Conversion,有谁能帮我在C中编写与linq等效的sql吗 select COUNT(ot.UserId) as orderCount, SUM(ot.TotalAmount) as TotalAmount, MAX(u.UserName) as UserName, MAX(c.name) as ClientName from OrderTemplate ot join User u on u.userid = ot.UserId join Client c on u.ClientID = c.client

有谁能帮我在C中编写与linq等效的sql吗

select 
COUNT(ot.UserId) as orderCount, SUM(ot.TotalAmount) as TotalAmount,
MAX(u.UserName) as UserName, MAX(c.name) as ClientName
from OrderTemplate ot
join User u
on u.userid = ot.UserId
join Client c
on u.ClientID = c.clientid
group by ot.UserId
我所做的是

from ot in dbContext.OrderTemplates
join user in dbContext.Users on ot.UserId equals user.UserID
join client in dbContext.Clients on user.ClientID equals client.ClientID
group ot by ot.UserId into g
select new 
{ 
    //UserName = need to pick this from user table
    //ClientName = need to pick this from client table
    OrderCount = g.Count(),
    TotalAmount = g.Sum(x=> x.TotalAmount)
};

我无法根据sql选择值。

因此,如果用户名和客户端名称相同,并且实际上每个订单都有一个客户端和一个用户,则最好通过多个键进行分组:

from ot in dbContext.OrderTemplates
join u in dbContext.Users on ot.UserId equals u.UserID
join c in dbContext.Clients on u.ClientID equals c.ClientID
group ot by new { ot.UserId, u.UserName, c.ClientName } into g
select new 
{ 
    UserName = g.Key.UserName,
    ClientName = g.Key.ClientName,
    OrderCount = g.Count(),
    TotalAmount = g.Sum(x=> x.TotalAmount)
};
如果它们不是,或者如果您希望与sql完全相同,则在实例化匿名对象时,不要使用具有多个属性的键:

Username = g.Max(item => item.UserName) // will just use string comparison to select the "max"

用户名的值是什么?Maxu.Username实际上是什么意思?这些是相同的用户名吗?是否有些值为null,然后您使用max来获取不为null的值?是的,每个组的用户名都是相同的,所以我只需要选择任何一个。在sql中,您是通过UserId进行搜索的,但在linq中是通过OrderId进行搜索的