How to change orderby on postback for LINQ to SQL query
I have a drop down list set to auto post back which needs to return a list of products in the specified order. I thought I could just put that query in its own method and use a parameter to specify the orderby, but I cannot get it to work.
Here is an example:
protected void Show_Products(int item)
{
开发者_StackOverflow社区 using (storeDataContext db = new storeDataContext())
{
string query = "";
switch (item)
{
case 1:
query ="x.Name";
break;
case 2:
query = "x.MSRP";
break;
default:
break;
}
var q = db.Items.OrderBy(x=> query).Select(x => x);
foreach(var n in q)
{
Do work
}
}
}
And the drop down list method that gets called on postback:
protected void ddlSortBy_SelectedIndexChanged(object sender, EventArgs e)
{
int value =int.Parse(ddlSortBy.SelectedValue);
Show_Products(value);
}
var q = from p in db.Items
select q;
switch(item)
{
case 1:
q.OrderBy(x=> x.Name);
break;
case 2:
q.OrderBy(x=> x.MSRP);
break;
default:
break;
}
foreach(var n in q)
{
// Do work
}
I took one look at that book of code someone linked and knew there was a way to do it. Low and behold I was right.
protected void Show_Products(int item)
{
using (storeDataContext db = new storeDataContext())
{
var q = db.Items.OrderBy(x=> x.Name).Select(x => x);
switch (item)
{
case 1:
var q = db.Items.OrderBy(x=> x.Name).Select(x => x);
break;
case 2:
q = db.Items.OrderBy(x => x.MSRP).Select(x => x);
break;
default:
break;
}
foreach(var n in q)
{
Do work
}
}
}
I initially set var q to a query for initialization, but it doesn't matter because this method will be passed a parameter which will change it.
It may not be the most elegant way, but for only a few options I think it is doable.
Sorry, but what you are trying to do is using a Literal "x.Name"
and "x.MSRP"
to access methods.. you don't do it unless you are using Reflection to get Method and Properties.
精彩评论