LINQ中的行号

Dot*_*row 6 linq linq-to-entities entity-framework-4

我有这样的linq查询:

var accounts =
    from account in context.Accounts
    from guranteer in account.Gurantors
     where guranteer.GuarantorRegistryId == guranteerRegistryId
    select new AccountsReport
    {
        recordIndex = ?   
        CreditRegistryId = account.CreditRegistryId,
        AccountNumber = account.AccountNo,
    }
Run Code Online (Sandbox Code Playgroud)

我想使用LINQ返回的集合中的当前行号的值填充recordIndex.我怎样才能获得行号?

Lad*_*nka 13

linq-to-entities不支持行号.您必须首先从没有行号的数据库中检索记录,然后通过linq-to-objects添加行号.就像是:

var accounts =
    (from account in context.Accounts
     from guranteer in account.Gurantors
         where guranteer.GuarantorRegistryId == guranteerRegistryId
     select new
         {  
             CreditRegistryId = account.CreditRegistryId,
             AccountNumber = account.AccountNo,
         })
    .AsEnumerable()  // Moving to linq-to-objects 
    .Select((r, i) => new AccountReport
         {
             RecordIndex = i,  
             CreditRegistryId = r.CreditRegistryId,
             AccountNumber = r.AccountNo,
         });
Run Code Online (Sandbox Code Playgroud)


Sti*_*gar 0

尝试像这样使用 let :

int[] ints = new[] { 1, 2, 3, 4, 5 };
int counter = 0;
var result = from i in ints
             where i % 2 == 0
             let number = ++counter
             select new { I = i, Number = number };

foreach (var r in result)
{
    Console.WriteLine(r.Number + ": " + r.I);
}
Run Code Online (Sandbox Code Playgroud)

我现在无法使用实际的 LINQ to SQL 或实体框架对其进行测试。请注意,上面的代码将在多次执行查询之间保留计数器的值。

如果您的特定提供商不支持此功能,您始终可以 foreach (从而强制执行查询)并在代码中手动分配号码。