C#lambda->所有行选择Add Row_Number

时间:2016-02-29 08:15:58

标签: c# sql linq lambda

我有一张桌子:

DataTable store_temp = new DataTable(); 
store_temp.Columns.Add("patn");
store_temp.Columns.Add("rf");
store_temp.Columns.Add("name");
store_temp.Columns.Add("conv");
store_temp.Columns.Add("conv_type");
store_temp.Columns.Add("recorddate");
store_temp.Columns.Add("executiondate");

我的C#代码:

int i = 0;
var rowsgroups = (from row in store_temp.AsEnumerable().GroupBy(row =>
row.Field<string>("patn"))
.OrderBy((g => g.OrderByDescending(y => y.Field<string("executiondate")).ThenByDescending(y =>
y.Field<string>("rf"))))
select new
{
    patn = row.ElementAt(i),
    rf_num = ++i,
}).ToArray();

我想要lambda exression,相当于:

  
select patn, rf,
         

&GT; row_number()over(按执行日期的分区按顺序排序,rf)     作为rf_num,

  
     name, conv,conv_type, recorddate, executiondate 
      from store_temp2

但是,lambda语法... var rowsgroups只有一行.. 我想在store_temp中显示所有行。 我该怎么做才能修复查询?

3 个答案:

答案 0 :(得分:1)

  

row_number()结束(按执行日期分配patn顺序,rf)

表示在LINQ中,您需要按patn分组,然后按executiondate, rf命令每个组,然后使用索引Select重载来获取内部行编号小组,最后用SelectMany展平结果。

话虽如此,等效的LINQ查询可能是这样的:

var result = store_temp.AsEnumerable()
    .GroupBy(e => e.Field<string>("patn"), (key, elements) => elements
        .OrderBy(e => e.Field<string>("executiondate"))
        .ThenBy(e => e.Field<string>("rf"))
        .Select((e, i) => new
        {
            patn = key,
            rf = e.Field<string>("rf"),
            rf_num = i + 1,
            name = e.Field<string>("name"),
            conv = e.Field<string>("conv"),
            conv_type = e.Field<string>("conv_type"),
            recorddate = e.Field<string>("recorddate"),
            executiondate = e.Field<string>("executiondate")
        }))
    .SelectMany(elements => elements)
    .ToArray();

答案 1 :(得分:0)

尝试这样的事情

select new
{
    rowNum = store_temp.Rows.IndexOf(row),
    patn = row.ElementAt(i),
    rf_num = ++i,
}).ToArray();

答案 2 :(得分:0)

根据您的groupby

,我认为您不需要任何required sql
        var i=0;
        var rowsgroups = (from row in store_temp.AsEnumerable()
                          orderby row.Field<string>("executiondate") descending,
                          row.Field<string>("rf") descending
                          select new
                            {
                                patn = row.Field<string>("patn"),
                                rf_num = ++i,
                                name = row.Field<string>("name"),
                                conv = row.Field<string>("conv"),
                                conv_type = row.Field<string>("conv_type"),
                                recorddate = row.Field<string>("recorddate"),
                                executiondate = row.Field<string>("executiondate") 
                            }).ToArray();