English 中文(简体)
SQL查询到Linq GroupBy和Max
原标题:SQL Query to Linq GroupBy and Max

这里是一个我正在尝试转换成Linq的SQL查询。如果相关的话,我正在使用一个对象的通用列表而不是DataTable。

Select Max(Date), ID, Property1, Peroperty2 From List Group By ID

请帮忙。

最佳回答

尽管您的SQL不是有效的,因为Property1Property2必须是聚合的一部分,但这将按ID、Property1、然后按照这个顺序的Property2分组,这是我认为您正在寻找的东西。

from obj in List
group obj by new {obj.ID, obj.Property1, obj.Property2 } into g
select new 
       { 
          ID = g.Key.ID, 
          Property1 = g.Key.Property1, 
          Property2 = g.Key.Property2,  
          MaxDate = g.Max(p => p.Date) 
       }

相当于:

Select Max(Date), ID, Property1, Peroperty2 
From List 
Group By ID, Property1, Property2
问题回答

正如Steve所说,没有在聚合子句中包含Property1等,你的SQL是无效的。然而,我觉得你是在尝试获取那些日期等于按Id分组后的行的最大日期的数据?

这个工作方式是这样的:

recs.GroupBy(r => r.Id).SelectMany(g => g.Where(r => r.Date == g.Max(a => a.Date)))

按Id分组,获取日期与该组的最大日期相匹配的项目的IEnumeration,并将它们展平为单个IEnumeration - 然后可以迭代或做任何您想做的事情。

顺便说一下,在查询语法中,我最好能做到的是类似于:

from r in recs
where r.Date ==
    (from sr in recs
     where sr.Id == r.Id
     select sr.Date).Max()
select r;

编辑2:

这实际上更像:

recs.Where(r => r.Date == recs.Where(sr => sr.Id == r.Id).Max(a => a.Date)).Select(r => r)

以流畅的语法呈现,但对我来说不如我第一种方式的呈现方式好看...我不是特别喜欢查询表达式语法,这很有趣,因为我对SQL很熟悉,查询语法应该更像SQL。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签