so, i have a method: I'm counting a number in a sequence with holes, this number should be the first hole or max()
public static int GetRegisterNumber<T>(this IQueryable<T> enumerable, Func<T, bool> whereFunc, Func<T, int?> selectFunc)
{
var regNums = enumerable.OrderBy(selectFunc).Where(whereFunc).ToArray();
if (regNums.Count() == 0)
{
return 1;
}
for (int i = 0; i < regNums.Count(); i++)
{
if (i + 1 != regNums[i])
{
return regNums[i].Value + 1;
}
}
return regNums.Last().Value + 1;
}
i use it like:
var db = new SomeDataContext();
db.Goals.GetRegisterNumber(g => g.idBudget == 123, g => g.RegisterNumber);
So, i expect from linq some query like:
SELECT [t0].[id], [t0].[tstamp], [t0].[idBudget], [t0].[RegisterNumber], FROM [ref].[GoalHierarchy] AS [t0] WHERE [t0].[idBudget] = 123 ORDER BY [t0].[RegisterNumber]
instead i'm getting:
SELECT [t0].[id], [t0].[tstamp], [t0].[idBudget], [t0].[RegisterNumber], FROM [ref].[GoalHierarchy] AS [t0]
So linq gets ALL the table data and then filters it, but that behavior is not acceptable, because the table contains much data. Is there any solution?
Change your method signature to look like this:
This way it will call the appropriate extension methods for
IQueryable<T>
. If you only have aFunc<TSource, bool>
, it will call the extension method forIEnumerable<T>
.