Linq and OrderBy

I

Ilyas

Hi all

I have the following code

NorthwindDataContext nw = new NorthwindDataContext();
string orderByFieldName = "ProductName";
var data1 = (from p in nw.Products orderby
orderByFieldName select p);

This obviouslay doesnt work, what am I doing wrong. I want the ability
to sort on a column name - how can I do this?
 
J

Jon Skeet [C# MVP]

Ilyas said:
I have the following code

NorthwindDataContext nw = new NorthwindDataContext();
string orderByFieldName = "ProductName";
var data1 = (from p in nw.Products orderby
orderByFieldName select p);

This obviouslay doesnt work, what am I doing wrong. I want the ability
to sort on a column name - how can I do this?

One of the purposes of LINQ is to make queries correct at compile time.

How many potential orderings do you have? You could do something like:

IEnumerable<Products> data1;
switch (orderByFieldName)
{
case "ProductName":
{
data1 = nw.Products.OrderBy(p => p.ProductName);
}
case "ProductID":
{
data1 = nw.Products.OrderBy(p => productID);
}
// etc
}

Alternatively, I believe Marc Gravell has some code to produce an
appropriate expression tree from a property name if you really want to
go that route.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top