tags:

views:

297

answers:

5

Hello,

Is there a way to build a linq query in order to use it later or to display/print it (and more specifically, the where clause) ?

A: 

Linq cannot be displayed (AFAIK), if you mean 'linq2sql' query (qg. sql query built from linq), no, it cannot be printed out.

Yossarian
myDataContext.GetCommand(query).CommandText ?
David B
@David B: mea culpa. Thanks for correcting, I didnt knew about this.
Yossarian
+1  A: 

Isn't LINQ a .NET 3.5-feature?

edit:

http://msdn.microsoft.com/en-us/library/bb332048.aspx

--> LINQ is only available from .NET 3.5, so not 3.0 as the topicstarter asks.

edit2:

Ok, so the TS talks about C# 3.0, which comes with .NET 3.5.

Quite confusing.

Natrium
Tag is for C#3.0 and that is the C# version that came with .NET 3.5. You doesn't deserve negative points for this IMO, though.
Petar Repac
LINQ syntax in C# is a C# 3.0 feature. LINQ implementations are .NET 3.5 features. C# 3.0 released simultaneously with .NET 3.5
David B
@Petar, these remarks should've been made as a comment, rather as an answer. It doesn't help the topic starter, it adds nothing but noise, and it's what comments are meant for...
Razzie
+8  A: 

What exactly is it you want? You can capture just the expression from the Where - something like:

Expression<Func<SomeType, bool>> predicate = row => row.IsActive
          && row.Color == "red";

Because this is going to an expression tree, there is a meaningful ToString().

If you want the SQL (etc), then that will be implementation-specific. For example, with LINQ-to-SQL you can use .Log - for example, ctx.Log = Console.Out;

If you want the predicate out of the middle of an IQueryable<T> feed, then that is much trickier...

Marc Gravell
can i use an expression as a where clause ? eg : IEnumerable<User> users = from u in GetAllUsers() where myExpression select u . With my expression beeing Expression<Func<User, bool>> ?
Toto
Yes, but as `... = GetAllUsers().Where(myExpression) ...`
Marc Gravell
Note that if `GetAllUsers()` returns `IEnumerable<T>`, you'll need to use `.AsQueryable().Where(myExpression)`
Marc Gravell
works really fine
Toto
A: 

You could look at System.Linq.Dynamic its a addon to linq to build dynamic where, orderby etc.

eg tblProduct.Where("product_id = @0", product_id)

That might be of some assistance.

Matthew Hood
A: 

Look at this example from MSDN:

// Lambda expression as executable code.
Func<int, bool> deleg = i => i < 5;
// Invoke the delegate and display the output.
Console.WriteLine("deleg(4) = {0}", deleg(4));

// Lambda expression as data in the form of an expression tree.
System.Linq.Expressions.Expression<Func<int, bool>> expr = i => i < 5;
// Compile the expression tree into executable code.
Func<int, bool> deleg2 = expr.Compile();
// Invoke the method and print the output.
Console.WriteLine("deleg2(4) = {0}", deleg2(4));
Dewfy