LINQ通过清晰到SQL命令 [英] Linq to SQL order by with Distinct

查看:99
本文介绍了LINQ通过清晰到SQL命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的环境:在VS 2013 ASP.net和C#速成

My Environment: ASP.net and C# in VS 2013 Express.

我经历过很多类似的SO文章试图解决这一点。我的业余使用LINQ到SQL查询和C#一般。

I have been through many similar SO articles trying to work this out. I am amateur with Linq to SQL queries and c# in general.

我试图使用LINQ到SQL从一列获得前5名最近不同的值,然后将它们添加到列表中。我的应用程序是用C#和数据抽象一个.dbml文件asp.net。

I'm trying to use Linq to SQL to get the top 5 most recent distinct values from a column, then add them to a list. My application is asp.net using c# and a .dbml file for data abstraction.

我已经尝试过许多不同的方法。我要么得到非不同但排序列表,或者我得到明显的无序列表。我有这么远低于为

I've tried it many different ways. I either get non-distinct yet sorted list, or I get a distinct unsorted list. What I have so far is below

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);



我在想我的另类正在举行的ID列,或许我需要告诉它我希望它看起来的制造商一栏,但我还没有制定出如何/是否有可能做到这一点。

I'm thinking my "Distinct" is looking at the "ID" column, and perhaps I need to tell it I want it to look at the "manufacturer" column, but I haven't worked out how / if it's possible to do that.

我能做到这一点轻松使用storedproc,但我真的想用直接如果可能的C#代码来做到这一点。这是我的第一篇以SO,我希望我已经把它一起正常。任何帮助非常赞赏。

I could do this with ease by using a storedproc, but I'm really trying to do it with c# code directly if possible. This is my first post to SO, I hope I have put it together properly. Any help much appreciated.

感谢

推荐答案

我觉得你可以。使用GROUPBY做你想要的东西。

I think you can use the GroupBy to do what you want.

  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);

这篇关于LINQ通过清晰到SQL命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆