views:

174

answers:

5

I'm playing around with some Linq-SQL stuff, doing something like this:

var foo = from f in db.Foo where f.Bar > 5 select f;

which is all fine and dandy, and I know I can also do this:

var foo = from f in db.Foo where f.Bar > 5 select new { f.Bar, f.Baz };

What I want to know, is can I factor out the select part of that query, if I want to determine at runtime what parts of Foo to select? Such as:

var foo = from f in db.Foo where f.Bar > 5 select SomeMethodThatReturnsThePropertiesOfFooIReallyWant();

Edit to clarify: I'm looking for the syntax and return type of SomeMethod...().

If I wanted to do this some times:

select new { f.Bar, f.Baz };

but other times do this:

select new { f.Baz, f.Other };

Based on data in memory (without doing a giant case statement), how would i do that, if possible?

+2  A: 

Sure, although it's easier in the fluent syntax:

var query_foo = db.Foo.Where(f=>f.Bar >  5);
//  :
var foo =query_foo.Select(f=>SomeMethodThatReturnsEtc(f));
James Curran
I guess my real question is, what's the syntax of the SomeMethod()?
Jonas
What is the return type of SomeMethodThatReturnsEtc?
Terry Donaghe
A: 

I guess my real question is, what's the syntax of the SomeMethod()? – Jonas (an hour ago)

The way you want to do it, you can only return "object" from the method.

Strelok
A: 

You will need to build a little projection (Select) expression dynamically to tack on to your base query that filters. See one of the following for some examples:

Dynamic.cs in the dynamic query sample that ships with VS 2008

http://www.albahari.com/nutshell/predicatebuilder.aspx

A: 

you cannot return anonymous types from a function, so you would be stuck with declared types, which goes against your question, or Object, which will not be very helpful.

More to the point, what exactly do you expect to do with your result? If the members are actually unknown at compile time, I'm not sure what you can do with it...

Denis Troller
A: 

Sometimes the easiest thing to do is just create a simple data class with a bunch of public get; and set; so you can select your data into that class. If you are dealing with nullable types that will be pretty clear when you consume the data, though if it is all strings you might find something else cleaner when it comes time to consume the data.

A simple example

public class MyData { public string Bar {get;set;} public int? Baz {get;set;} public DateTime? {get;set;} }

var foo = from f in db.Foo where f.Bar > 5 select new MyData { Bar = f.Bar, Foo = f.Foo };

You can also separate your statements out like this if you want to have the select in a different place than the select statement, this will only hit the server when you try to enumerate it.

var foo = from f in db.Foo where f.Bar > 5 select f; var fooData = f.Select(new MyData .... }

jarrett