Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An expression tree may not contain an assignment operator?

Tags:

c#

linq

How can i increment the index value in linq statement.

  int headIndex = -1;
           // int itemIndex = -1;
            lst = (from xx in db.vwCustomizationHeaders
                   where xx.ProductID == pID
                   select new custHeader()
                   {
                       headIndex = headIndex++,// Guid.NewGuid(),
             }
like image 451
NoviceToDotNet Avatar asked Mar 01 '14 14:03

NoviceToDotNet


1 Answers

While you're creating this query in code:

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

It's actually executed at the database. And the database can't modify values in your code. So you can't increment that code-local value (headIndex) from the database. (Additionally, as @Kirk Woll pointed out, it's very bad practice to modify values like that in a select. A select should just fetch/build something, not alter state or produce side-effects.)

If all you're doing is updating that value, you don't need to use a select. You can add the count of records to the value directly:

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

The commented-out part suggests that you're also building a list of vwCustomizationHeaders though, something like this:

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

From there you can use the lst object to modify your counter:

headIndex += lst.Count();
like image 130
David Avatar answered Oct 03 '22 02:10

David