使用Distinct从Linq到SQL排序
本文关键字:SQL 排序 Linq Distinct 使用 | 更新日期: 2023-09-27 18:24:39
我的环境:VS 2013 Express中的ASP.net和C#。
我已经阅读了许多类似的SO文章,试图解决这个问题。我对Linq-to-SQL查询和c#一般来说都是业余爱好者。
我尝试使用Linq-to-SQL从一列中获取前5个最新的不同值,然后将它们添加到列表中。我的应用程序是使用c#和.dbml文件进行数据抽象的asp.net。
我试过很多不同的方法。我要么得到一个不明显但已排序的列表,要么得到了一个明显的未排序列表。到目前为止,我所拥有的低于
var Top5MFG = (from mfg in db.orders
where mfg.manufacturer.Length > 0 && mfg.customerid == "blahblahblahblahblah"<br />
select new {
manufacturer = mfg.manufacturer,
date = mfg.date_created
})
.Distinct()
.OrderByDescending(s => s.date);
我想我的"Distinct"是在看"ID"栏,也许我需要告诉它我想让它看"制造商"栏,但我还没有弄清楚如何/是否可以做到这一点。
我可以通过使用storedproc轻松地做到这一点,但如果可能的话,我真的会尝试直接使用c#代码。这是我给SO的第一篇帖子,我希望我已经把它整理好了。非常感谢您的帮助。
感谢
否Distinct
比较manufacturer
和date
对。如果您想通过manufacturer
获得不同的记录,那么我推荐DistinctBy
方法。它在MoreLINQ
库中。由于它是linq-to-sql中不支持的第三种库方法,因此您仍然可以通过从DB中获取记录来使用它,并在内存中执行其余操作
(from mfg in db.orders
where mfg.manufacturer.Length > 0 && mfg.customerid == "blahblahblahblahblah"
select new {
manufacturer = mfg.manufacturer,
date = mfg.date_created
})
.AsEnumerable()
.DistinctBy(x => x.manufacturer)
.OrderByDescending(s => s.date)
.Take(5);
我认为您可以使用GroupBy来执行您想要的操作。
var Top5MFG = db.orders
.Where (x => x.manufacturer.Length > 0 && x.customerid == "blahblahblahblahblah")
.GroupBy(mfg => mfg.manufacturer)
.Select(g => g.First())
.OrderByDescending(d => d.date_created );
.Take(5);
通过某个字段进行区分的一种方法是替换:
...
.Distinct()
...
带有:
...
.GroupBy(x => x.manufacturer )
.Select(g => g.First())
...