views:

86

answers:

1

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?

+2  A: 

Change your method signature to look like this:

public static int GetRegisterNumber<T>(this IQueryable<T> enumerable, Expression<Func<T, bool>> whereFunc, Expression<Func<T, int?>> selectFunc)

This way it will call the appropriate extension methods for IQueryable<T>. If you only have a Func<TSource, bool>, it will call the extension method for IEnumerable<T>.

Ryan Versaw
I haven't yet tested this, but I think it should work.
Ryan Versaw
thanks! that helped
xumix
+1 from me. My answer wasn't helpful as I misread the question, so I've deleted it.
RichardOD