LINQ中的行号

时间:2011-05-16 07:37:13

标签: 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 = ?   
        CreditRegistryId = account.CreditRegistryId,
        AccountNumber = account.AccountNo,
    }

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

5 个答案:

答案 0 :(得分: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,
         });

答案 1 :(得分:2)

LINQ to objects为任何枚举器都内置了这个:

http://weblogs.asp.net/fmarguerie/archive/2008/11/10/using-the-select-linq-query-operator-with-indexes.aspx

修改:虽然IQueryable也支持它(herehere),但有人提到这个对于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扩展方法(如.Where)和额外的索引参数重载

答案 2 :(得分:1)

尝试使用像这样:

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

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

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

答案 3 :(得分:0)

因为问题中的查询是按单个ID过滤的,所以我认为给出的答案不会有帮助。当然,你可以在内存客户端做到这一切,但是根据数据集的大小,以及是否涉及网络,这可能是一个问题。

如果您需要SQL ROW_NUMBER [..] OVER [..]等价物,我知道的唯一方法是在SQL服务器中创建一个视图并对其进行查询。

答案 4 :(得分:-1)

此测试和工作:

修改您的代码如下:

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

希望这会有所帮助..虽然已经晚了:)