views:

50

answers:

3

I need to write some dynamic queries for a project I'm working on. I'm finding out that a significant amount of time is being spent by my program on the Count and First methods, so I started to change to .Single, only to find out that there is no such method.

The code below was my first attempt at creating one (mostly copied from the Where method), but it's not working. Help?

 public static object Single(this IQueryable source, string predicate, params object[] values)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (predicate == null) throw new ArgumentNullException("predicate");
        LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, typeof(bool), predicate, values);
        return source.Provider.CreateQuery(
            Expression.Call(
                typeof(Queryable), "Single",
                new Type[] { source.ElementType },
                source.Expression, Expression.Quote(lambda)));
    }
+1  A: 

IMHO, you should just simply can use Single or SingleOrDefault when you are executing the query.

// build your dynamic query
var query = NorthwindConext.Products.Categories
                                    .Where("CategoryID = @0", 2);
// now you can simply get the single item by
var category = query.SingleOrDefault();

So, I do not see the necessity for a "Single" operator for dynnamic linq. Especially, as the IEnumerable or IQueryable returned by the query enumeration should only contain one item.

Obalix
Queryable.Single won't work out of the box b/c I need a dynamic query, one where the lambda expression is built as a string then parsed.
Yoenhofen
A: 

I think Queryable.Single is what you're looking for.

Gabe
Queryable.Single won't work out of the box b/c I need a dynamic query, one where the lambda expression is built as a string then parsed.
Yoenhofen
Just put the lambda into a `Where` and pass the result of that to `Queryable.Single`. It will do the same thing.
Gabe
+1  A: 

I don't understand what the difference you fill to be between Single(SingleOrDefault) and First(FirstOrDefault) ? Moreover EF do not implement the first one and you have to use First(FirstOrDefault) instead. Also why do you fill you will gain perfomance improvement by creating your own implementation of single , which is by your comment almost a copy of where , which is almost the same as first so why do not use it , and try to look at query's being generated and analyse them ?

vittore