选择使用LINQ到实体的连续条目 [英] Selecting Consecutive Entries with LINQ to Entities

查看:121
本文介绍了选择使用LINQ到实体的连续条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库表,每行包含一个顺序索引。我想基于此索引列选择连续的行组。例如,如果我有以下索引值的行:

I have a database table with rows that each contain a sequential index. I want to select groups of rows that are consecutive based upon this index column. For example, if I had rows with the following index values:

1
3
4
5
7
9
10
11
12
15
16

,我想选择所有具有3个连续索引的组(这个数字会有所不同)。我会得到以下组:

and I wanted to select all groups with 3 consecutive indices (this number will vary). I would get the following groups:

3, 4, 5

9, 10, 11

10, 11, 12

基本上,类似于此处提出的问题:

Basically, I'm trying to achieve something similar to the question posed here:

使用SQL查询选择连续的数字

但是,我想用LINQ to Entities实现,而不是实际的SQL。我也不喜欢使用存储过程,我不想做任何类型的ToList /循环方法。

However, I want to implement this with LINQ to Entities, not actual SQL. I would also prefer not to use stored procedures, and I don't want to do any sort of ToList/looping approach.

编辑:组超过请求的连续元件不一定需要分开。即在前面的例子中,9,10,11,12的结果也是可以接受的。

Groups with more than the requested consecutive elements don't necessarily need to be split apart. i.e. in the previous example, a result of 9, 10, 11, 12 would also be acceptable.

推荐答案

工作相当有效率(C#虽然):

I think this might work pretty efficiently (C# though):

int[] query = { 1, 3, 4, 5, 7, 9, 10, 11, 12, 15, 16 };
int count = 3;
List<List<int>> numbers = query
   .Where(p => query.Where(q => q >= p && q < p + count).Count() == count)
   .Select(p => Enumerable.Range(p, count).ToList())
   .ToList();

这篇关于选择使用LINQ到实体的连续条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆