LINQ中的行数

LINQ中的行数,linq,entity-framework-4,linq-to-entities,Linq,Entity Framework 4,Linq To Entities,我有这样一个linq查询: var accounts = from account in context.Accounts from guranteer in account.Gurantors where guranteer.GuarantorRegistryId == guranteerRegistryId select new AccountsReport { recordIndex = ? CreditReg

我有这样一个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,
    }

我想用LINQ返回的集合中当前行数的值填充recordIndex。如何获取行号?

尝试使用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);
}
我现在无法用实际的LINQtoSQL或实体框架来测试它。请注意,上面的代码将在多次执行查询之间保留计数器的值


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

LINQ to objects为任何枚举器都内置了此功能:

Edit:尽管IQueryable也支持它(而且),但已经提到,对于LINQ到SQL/实体,该不幸不起作用

new []{"aap", "noot", "mies"}
    .Select( (element, index) => new { element, index });                                  
将导致:

{ { element = aap, index = 0 }, 
  { element = noot, index = 1 }, 
  { element = mies, index = 2 } }

还有其他具有额外索引参数重载的LINQ扩展方法(如),LINQ to实体中不支持行数。必须首先从数据库中检索不带行号的记录,然后按linq向对象添加行号。比如:

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,
         });

因为问题中的查询只通过一个id进行过滤,所以我认为给出的答案没有帮助。当然,您可以在内存客户端完成这一切,但取决于数据集的大小,以及是否涉及网络,这可能是一个问题

如果您需要一个SQL
行号[…]超过[…]
的等效值,我知道的唯一方法是在SQL server中创建一个视图并根据该视图进行查询。

此方法经过测试并有效:

修改您的代码如下:

int counter = 0; 
var accounts =
    from account in context.Accounts
    from guranteer in account.Gurantors
     where guranteer.GuarantorRegistryId == guranteerRegistryId
    select new AccountsReport
    {
        recordIndex = counter++   
        CreditRegistryId = account.CreditRegistryId,
        AccountNumber = account.AccountNo,
    }

希望这有帮助。。虽然已经很晚了:)

为什么不使用LINQ内置支持?因为我不知道:)谢谢你指出了这一点。不要认为这会对LINQ to实体或LINQ to起作用SQL@Magnus:你说得对,它不适用于LINQ to SQL或LINQ to EF。@Magnus:,你测试过吗?@alex:好的,这让我很惊讶。关于这一点,将在回答中标记警告您的解决方案不起作用,而且它在recordIndex=counter++处有错误,应该是recordIndex=counter++,但它不起作用。请尝试使用实体和linqtosql