表达式树可能不包含赋值运算符?

时间:2014-03-01 14:31:00

标签: c# linq

如何在linq语句中增加索引值。

  int headIndex = -1;
           // int itemIndex = -1;
            lst = (from xx in db.vwCustomizationHeaders
                   where xx.ProductID == pID
                   select new custHeader()
                   {
                       headIndex = headIndex++,// Guid.NewGuid(),
             }

1 个答案:

答案 0 :(得分:6)

当您在代码中创建此查询时

from xx in db.vwCustomizationHeaders
where xx.ProductID == pID
select new custHeader()
{
    headIndex = headIndex++
}

它实际上是在数据库中执行。并且数据库无法修改代码中的值。因此,您无法从数据库中增加代码本地值(headIndex)。 (另外,正如@Kirk Woll所指出的那样,在select中修改类似的值是非常糟糕的做法。选择应该只是获取/构建一些东西,而不是改变状态或产生副作用。)

如果您所做的只是更新该值,则无需使用选择。您可以直接将记录计数添加到该值:

headIndex += db.vwCustomizationHeaders.Count(ch => ch.ProductID == pID);

已注释掉的部分表明您还在构建vwCustomizationHeader的列表,但是这样的话:

lst = (from xx in db.vwCustomizationHeaders
where xx.ProductID == pID
select new custHeader()
{
    SomeField = xx.SomeField,
    AnotherField = xx.SomeOtherField
    // etc.
});

从那里你可以使用lst对象来修改你的计数器:

headIndex += lst.Count();