tags:

views:

63

answers:

1

I'm new to linq, now I need to do flexible sorting with sort parameter specified. but

var query =
    from accessdoc in dt1.AsEnumerable()
     join content in dt2.AsEnumerable()
     on accessdoc.Field<string>("name") equals content.Field<string>("FileName")
    into docs
    orderby accessdoc.Field<DateTime>("CreateDate") descending //TODO: HOW TO SORT??

dose not meet the demand. Can I be helped out here?

A: 

Since linq is late binding you can do your query and then apply your sort separately. If you can split up how you do the sort parameter slightly, you could do something like this: (this code hasn't been compiled, so please bear with me)

public enum SortDirection
{
   Ascending = 0,   //default value
   Descending = 1
}

now if you pass in the linq expression and the direction, you could do something like this:

public IQueryable<MyObject> GetWithSort(System.Linq.Expressions.Expression<Func<MyObject, TKey>> sortExpression, SortDirection direction)
{
    var results = from accessdoc in dt1.AsEnumerable()
         join content in dt2.AsEnumerable()
         on accessdoc.Field<string>("name") equals content.Field<string>("FileName")
        into docs
        select...;

   if (direction == SortDirection.Descending)
      return results.OrderByDescending(sortExpression);

   return results.OrderBy(sortExpression)
}

select... will have to be replaced with however you are selecting your objects out of the linq statement.

Josh