Dillie-O
Dillie-O

Reputation: 29755

How do I sort the resulting list from an EF Query?

I have an entity mapped up to my database and can get a query to a list using the following code:

Dim Teams As New List(Of Team)

Teams = (From t In sdContext.Teams _
         Order By t.Name _
         Select t).ToList()

What I'd like to do is to parameterize the sort results on this query. Sometimes the user will sort it through based off the name, sometimes based off the description, sometimes based off the e-mail address.

I don't think I can properly setup the EF query to sort the results, so I'm looking to sort the results in the List. How can I do this? Does EF already have the IComparer or Predicate functions in place?

Upvotes: 0

Views: 389

Answers (3)

Chris Marais
Chris Marais

Reputation: 411

it looks like a similar question was asked here with a reference to this msdn article

ObjectQuery<Teams> teamsQuery = db.Teams.OrderBy("it.Name");
List<Teams> teams = teamsQuery.ToList();

Upvotes: 1

Brian Cauthon
Brian Cauthon

Reputation: 5534

You can do your sort at the DB. I would create a class OrderSortCriteria

public class OrderSortDefinition{
    public bool ByName { get; set;}
    public bool ByEmail { get; set; }
    public bool ByDescription { get; set; }
}

I would use this when building my query to add the appropriate sort.

public IList<Team> GetSortedTeams(OrderSortDefinition sortOrder){    
    var teams = from t in sdContext.Teams
                select t;
    if(sortOrder.ByEmail){
        return teams.OrderBy(t=>t.Email).ToList();
    }

    // repeat for each field.
}

You could make your OrderSortDefinition more complex if you need to support sorting on multiple fields.

Upvotes: 0

Tomas McGuinness
Tomas McGuinness

Reputation: 7689

You can order using a predicate passed into the OrderBy LINQ method:

var list = sdContext.Teams.OrderBy(t => t.Name).ToList()

Or take the output from your original statement and the just order the List you create.

Upvotes: 0

Related Questions