Reputation: 652
This is my (simplified) code:
Controller
var userQuery = from u in _db.Users
where u.Username.ToLower().Contains(search.ToLower())
|| u.FirstName.ToLower().Contains(search.ToLower())
|| u.LastName.ToLower().Contains(search.ToLower())
select u.FirmID;
var query = from f in _db.Firms
where f.Name.ToLower().Contains(search.ToLower())
|| f.Keyword.ToLower().Contains(search.ToLower())
|| f.KeywordList.ToLower().Contains(search.ToLower())
|| userQuery.Contains(f.ID)
select f;
// order by firm name
query = query.OrderBy(f => f.Name);
User Model
public class User
{
[Key]
public int ID { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int FirmID { get; set; }
[ForeignKey("FirmID")]
public virtual Firm Firm { get; set; }
}
Firm Model
public class Firm
{
[Key]
public int ID { get; set; }
public string Keyword { get; set; }
public string KeywordList { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
With this code, I get a list of Firms with Users which matches a certain search string. The list is ordered by Firms name. What I wanna do now, is to sort also by Users last name. How can I do that?
Now:
Desired:
Upvotes: 0
Views: 206
Reputation: 652
Well, I finally found the best solution for me:
query.OrderBy(f => f.Name)
.ToList()
.ForEach(f => f.Users = f.Users.OrderBy(u => u.LastName).ToList() );
This means, I don't have to create an anonymous select object (like Jorge's answer), which makes the model a lot easier to handle in a view.
Another solution could be to sort the users not in the controller but in the view. For example:
@foreach (var user in Model.Users.OrderBy(u => u.LastName)) { }
Upvotes: 0
Reputation: 18257
tried like this
query.OrderBy(f => f.Name).Select(aux => new
{
Firm = aux.Firm,
Users = aux.Users.OrderBy( x => x.Username )
})
Upvotes: 1