我需要将查询从 sql 转换为 linq 创建表历史记录
CREATE TABLE [dbo].[History](
[HistoryID] [int] IDENTITY(1,1) NOT NULL,
[AuctionID] [int] NOT NULL,
[UserName] [nvarchar](128) NULL,
[Time] [datetime] NOT NULL,
[Price] [decimal](18, 2) NOT NULL,
)
查询
select [UserName],[Price] from [History]
where [Price] in
(SELECT [Price] FROM [History]
where ID=28 GROUP BY [Price]
HAVING COUNT(*)=1)
Order by [Price]
最佳答案
我认为您正在寻找与您的 SP 类似的 LINQ
语句。使用下面的一个
// Using Plain LINQ statements
var result1 = from history in lstHistory
where history.ID == 28
group history by history.Price into g
orderby g.Key
where g.Count() == 1
select new
{
Price = g.Key,
UserName = g.Select(h => h.UserName).FirstOrDefault()
};
或者
// Using Lambda Expressions
var result2 = lstHistory
.Where(q => q.ID == 28)
.OrderBy(t => t.Price)
.GroupBy(h => h.Price)
.Where(grp => grp.Count() == 1)
.Select(g => new
{
Price = g.Key,
UserName = g.Select(h => h.UserName).FirstOrDefault()
});
关于Linq to SQL 嵌套选择组(按计数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13238087/