简体   繁体   English

在Linq2Sql或实体框架查询中查找记录位置

[英]Find record position in Linq2Sql or Entity framework query

I'm trying to implement IBindingListView that will work with any Linq query as data source, but I'm stuck on the implementation of Find(PropertyDescriptor, Object) method which should find position of the record containg some value in specific property. 我正在尝试实现将与任何Linq查询一起用作数据源的IBindingListView ,但是我坚持使用Find(PropertyDescriptor,Object)方法的实现,该方法应该在特定属性中查找包含某些值的记录的位置。

I don't want to iterate over all records in memory. 我不想遍历内存中的所有记录。 I want database to do it. 我要数据库去做。
Unfortunately Linq doesn't support row_number() SQL function and I'm unable to find any other way to do it while preserving ordering and filtering. 不幸的是,Linq不支持row_number()SQL函数,在保留顺序和过滤的同时,我找不到其他方法。

In other words: 换一种说法:
Given 给定

class Entity
{
   public string StringProperty {get; set;}
   public int IntProperty {get; set;}
   public string StringProperty2 {get; set;}
}

|StringProperty | IntProperty | StringProperty2|
|ccc            | 102         | value 2        |
|aaa            | 100         | value 0        |
|ddd            | 103         | value 3        |
|aaa            | 101         | value 1        |

and query 和查询

var query = from e in Entities
            where e.IntProperty > 100
            orderby e.StringProperty

Which gives me 这给了我

|StringProperty | IntProperty | StringProperty2|
|bbb            | 101         | value 1        |
|ccc            | 102         | value 2        |
|ddd            | 103         | value 3        |

Find() with arguments StringProperty2 = 'value 2' should return 1 (0 based index), but it should be found using Linq so that it will be executed in database. 具有StringProperty2 = 'value 2'参数的Find()应该返回1(基于0的索引),但是应该使用Linq查找它,以便它将在数据库中执行。

I don't have a problem if there will be 2 or 3 queries executed, but please don't assume I know anything about primary keys or specific Linq provider. 如果执行2或3个查询,我没有问题,但是请不要以为我对主键或特定的Linq提供程序一无所知。 We can assume that if Linq to SQL or Entity Framework is able to translate something to SQL than it can be used. 我们可以假设,如果Linq to SQL或Entity Framework能够将某些内容转换为SQL,则可以使用它。

How can I implement IBindingListView.Find() method that works on any Linq query as a data source? 如何实现可在任何Linq查询上用作数据源的IBindingListView.Find()方法?

You can use lambda expression form for capture row data and row index. 您可以使用lambda表达式形式来捕获行数据和行索引。 Example: 例:

var query = youCollection
            .Select((r, i) => new {Row = r, Index = i});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM