【问题标题】:get row index in Linq query在 Linq 查询中获取行索引
【发布时间】:2019-07-11 02:25:54
【问题描述】:

我想从 LINQ 查询中获取结果集中行的索引。

int i = 0;
if (methodId == 4 || methodId == 7)
{
    sessions = db.sessions
        .Where(x => x.id == Id)
        .Select(x => new feeList
        {
            id = x.id,
            title = "Title: " + (i++)
        })
        .ToList();
}

我尝试添加i++,但消息an expression tree may not contain an assignment operator 出现错误。

如何将结果集中的行索引添加到我的title 变量中。

【问题讨论】:

    标签: asp.net sql-server linq


    【解决方案1】:

    (推荐版本)因为EF LINQ不支持An expression tree may not contain an assignment operator,所以你必须使用ExecuteQuery + SQL row_number()函数。

    sessions = db.ExecuteQuery<feeList>(@"
            select id,
                'Title: ' + convert(varchar(10),row_number() over (order by id)) title 
            from session where ID = {0}"
            , id).ToList();
    

    (不推荐版本)或者如果您的数据很小并且您不想使用sql,那么您可以使用ToList + select((object,index)=&gt; YourLogic),因为ToList会将SQL发送到DB并将数据获取到内存然后系统将使用@ 987654327@,所以支持assignment operator

    sessions = db.sessions
        .Where(x => x.id == Id).ToList()
        .Select((x,i) => new feeList
        {
            id = x.id,
            title = $"Title: {i}"
        })
        .ToList();
    

    PS,索引从 0 开始:

    new[] {"obj1","obj2"}.Select((obj, index) => new {obj,index})
    
    Result : 
    objc    index
    obj1    0
    obj2    1
    

    【讨论】:

    • Select((x,i) 是一种将 linq 用于对象的好方法。但对于 OP 来说,了解在查询开始时执行 ToList() 的含义非常重要,并且在内存中处理以下行。另一种解决方案是在 SQL 端处理索引,例如在视图或存储过程中。
    • 是的,ToList + Select((x,i)) 只能用于非常小的数据,但仍然不推荐。这个问题应该使用row_number sql
    猜你喜欢
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    相关资源
    最近更新 更多