2

How can i convert linq to object query or any other Func delegate to string like sql statements

for example

var cat_list = new List<Cat> { ... };

var myquery = cat_list.Where(x => x.Age > 2 && x.Name.Contains("Kitty"));

Now myquery is IEnumerable<Cat>. how can i convert this to simply something like this

"Age > @p1 AND Name LIKE @p2"

how can i achieve this ??

4
  • Unsure what you're actually asking. You'd like to take any given IQueryable<T> (which has had a .Where() applied to a list, and convert it into a SQL-like statement? Commented Jul 24, 2011 at 16:15
  • 1
    In your code, myquery is IEnumerable<Cat>. Commented Jul 24, 2011 at 16:16
  • yes, that's it. actually i mean to take the condition part which has been applied to the list and convert this condition to sql like statement. Commented Jul 24, 2011 at 16:17
  • @svick yes, you're right, I missed this,. Commented Jul 24, 2011 at 16:19

3 Answers 3

2

Doing something like that is not simple. Have a look at the series of articles Building an IQueryable provider by Matt Warren. All the code he uses is available as a library too. That should help you get started.

Sign up to request clarification or add additional context in comments.

Comments

1

You could write an expression tree parser and generate the sql. Your description contains a fault - myquery isn't IQueryable<Cat>, it is an IEnumerable<Cat>. As you tagged it correctly, this is linq-to-objects, not linq-to-sql. There is no information in the calls to construct a query.

1 Comment

I knew, and I think that this is because the linq to object is executed entirely in memory, on the opposite the linq to sql has a part that is executed on the DB engine itself. but is there is any kind of expression parser that go through the expression tree and generate this sql like statemtn ?
0

Check out the method DataContext.GetCommand() which is passed an IQueryable object and returns the DbCommand object that corresponds to the query. The CommandText property of the DbCommand object shows the text of the query.

1 Comment

no actually this is linq to object not linq to sql, thanks for cooperation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.