LINQ to SQL Dynamic Sort question
How do I code the Select clause in my LINQ satament to select column aliases so I can sort on them basically I want to accomplish this SQL statement in LINQ:
select
type_id as id,
type_desc as description
from
dbo.equip_type_avt
order by
description
What do I replace the ????? in my .Select clause in my LIN开发者_如何学编程Q statement?
public IQueryable<equip_type_avt> GetGridEquipmentTypes(string sidx, string sord)
{
try
{
return
ulsDB.equip_type_avts
.Select(?????)
.OrderBy(sidx + " " + sord);
}
catch (Exception ex)
{
string strErr = ex.Message;
return null;
}
}
You can use an anonymous type:
table.Select(x => new
{
ID = x.type_id,
Description = x.type_desc
});
However, you can't access the properties of an anonymous type outside of the scope where it is declared (without reflection or other dirty hackery, anyway) so if you want to use the result outside of that function you just create a class and create an instance of it in the query using a type initializer:
public class Foobar
{
public int ID { get; set; }
public string Description { get; set; }
}
...
table.Select(x => new Foobar() // Note the difference here
{
ID = x.type_id,
Description = x.type_desc
});
Question though: if you want to name the columns differently, why don't you change it in the place where the column-property mapping is declared? In LINQ-to-SQL you can have the database column be named whatever you like but give the property the name "ID" or "Description".
I'm not sure i understand your question, how does sidx and sord relate to your query?
Isn't your problem rather that you have to end your query with OrderBy(...).ThenBy(...) instead of a combined OrderBy?
If you want to sort by a string in the easy way, download the Dynamic LINQ library.
However, that's 2000 lines of code, most of which are entirely redundant for just the purpose of sorting.
Doing it yourself shouldn't be too hard, but requires a fair bit of knowledge on expression trees. I can't really help you there though.
EDIT: I've added another answer, that hopefully answers your actual question :)
精彩评论