views:

103

answers:

3

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 LINQ 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;
        }

    }
+1  A: 

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?

Per Hornshøj-Schierbeck
please see comment to JulianR.
MikeD
A: 

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 :)

JulianR
I should re-ask my question more clearly. I already have sorting working. I want to return my results as column names of 'ID' and 'Description' rather than 'type_id' and 'type_desc' which are the actual column names. Its easy in a SQL statement using the as clause. How do I accomplish the same thing using the the Select operator.
MikeD
+2  A: 

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".

JulianR
Thanks. Actually I wanted to use my function as a
MikeD