Linq to SQL order by Distinct

时间:2014-09-26 21:03:48

标签: c# linq linq-to-sql

我的环境:VS 2013 Express中的ASP.net和C#。

我经历了许多类似的SO文章试图解决这个问题。我是Linq to SQL查询和c#的业余爱好者。

我正在尝试使用Linq to SQL从列中获取前5个最新的不同值,然后将它们添加到列表中。我的应用程序是使用c#的asp.net和用于数据抽象的.dbml文件。

我尝试了很多不同的方法。我要么得到非独特但排序的列表,要么我得到一个明确的未排序列表。到目前为止我所拥有的是

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的第一篇文章,我希望我能把它正确地放在一起。任何帮助非常感谢。

由于

3 个答案:

答案 0 :(得分:1)

没有Distinct比较manufacturerdate对。如果您希望按manufacturer获取不同的记录,那么我建议DistinctBy方法。它&#39 ; s在MoreLINQ库中。由于它是第三个库方法,它在linq到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);

答案 1 :(得分:1)

您可以通过某个字段区分的一种方法是替换:

...
.Distinct()
...

使用:

...
.GroupBy(x => x.manufacturer )
.Select(g => g.First())
...

答案 2 :(得分:1)

我认为你可以使用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);
相关问题