在这个特定的例子中,我如何获得每组中的第一条记录?

时间:2016-08-16 19:41:33

标签: c# sql linq

在下面的代码中,我如何获得每组中的第一条记录?我真正的查询更复杂,我必须创建匿名类型,然后在我创建的dtResult表上使用LoadDataRow。我需要这样做,所以我可以在我的结果上使用CopyToDataTable功能:

           var results =
            (from cust in customers
             join invoice in invoices
             on
                 new
                 {
                     Prefix = cust.Field<string>("Prefix"),
                     CustNumb = cust.Field<int>("CustomerNumber")),
                     Suffix = cust.Field<int>("Suffix"))
                 }
             equals
                 new
                 {
                     Prefix = invoice.Field<string>("Prefix"),
                     CustNumb = invoice.Field<int>("CustomerNumber"),
                     Suffix = invoice.Field<int>("Suffix")
                 }
             group cust by new
             {
                 Prefix = cust["Prefix"],
                 CustomerNumber = cust["CustomerNumber"],
                 Suffix = cust["Suffix"],
                 Name = cust["Name"],
                 Address = cust["Address"]
             }
             into groups
             orderby groups.Key.Name
             // how do I get only the first record of each group?
             select dtResult.LoadDataRow(
                new object[]
                {
                    groups.Key.Prefix,
                    groups.Key.CustomerNumber,
                    groups.Key.Suffix,
                    groups.Key.Name,
                    groups.Key.Address
                }, false) 
             );

0 个答案:

没有答案