program sort order with linq

L

Luna

how can I modify a linq query programmatically? or do I need to write out
multiple queries?


enum SortOrder {
byName,
byTime,
ById,
ByNameDesc,
...
}


public IList<something> GetSomething(SortOrder queryOrder)
{
var a= from t in database.Test
//insert orderby here according to queryOrder value
select t;

return a
}

thank you
Luna
 
J

Jon Skeet [C# MVP]

how can I modify a linq query programmatically? or do I need to write out
multiple queries?

enum SortOrder  {
    byName,
    byTime,
    ById,
    ByNameDesc,
    ...

}

public IList<something> GetSomething(SortOrder queryOrder)
{
    var a= from t in database.Test
    //insert orderby here according to queryOrder value
    select t;

    return a

}

public IList<something> GetSomething(SortOrder queryOrder)
{
IQueryable<something> query = database.Test;

switch (queryOrder)
{
case SortOrder.ByName:
query = query.OrderBy (x => x.Name);
break;
case SortOrder.ByTime:
query = query.OrderBy (x => x.Time);
break;
case SortOrder.ById:
query = query.OrderBy (x => x.Id);
break;
case SortOrder.ByNameDesc:
query = query.OrderByDescending (x => x.Name);
break;
}

return query.ToList();
}
 
D

DabblerNL

You change the enum to Action<Something> delegate variables:
Action<Something> byName= element=>element.Name;
Action<Something> byTime= element=>element.Time;

public List<Something> GetOrederedList(IQueryable<Something>
unorderedCollection, Action<Something> sortAction)
{
var result=from element in unorderedCollection
orderby sortAction,
select element;
return result.ToList();
}
 

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