Reputation: 356
I am trying to sort a nested array of elements in asp.net and having a bit of trouble. Currently I have a playlist which has a model as so:
public class Playlist
{
public Playlist()
{
this.date = new List<dates>();
}
[Key]
public int id { get; set; }
public string UserId { get; set; }
public List<dates> date { get; set; }
public class dates
{
[Key]
public int dates_id { get; set; }
public List<places> place {get; set;}
}
public class places
{
[Key]
public int places_id { get; set; }
public string id { get; set; }
}
}`
As you can see it is a nested array of objects, dates, with another array of objects, places.
What I am doing now is pulling out the data as so:
playlist = db.Playlists.Where(e => e.UserId.Equals(userId)).OrderBy(q => q.id).Include("date.place").ToList();
What I realized was that the places in the date object wasn't being pulled out in a sorted array based on the place_Id, but rather randomly. Is there a way that I could pull out the playlist with the places ordered? The .OrderBy(q => q.id) would only pull an ordered list for the playlist and not the nested objects.
Upvotes: 0
Views: 1552
Reputation: 6882
You can arrange the order of items in nested lists on the client:
// Fetch playlists given a user id
var playlist = db.Playlists
.Where(e => e.UserId.Equals(userId))
.OrderBy(q => q.id)
.Include("date.place")
.ToList();
// Order places and dates by their id's
foreach(var item in playlist)
{
foreach(var d in item.dates)
{
d.places.Sort((left, right) =>
left.id.CompareTo(right.id));
}
item.dates.Sort((left, right)=>
left.id.CompareTo(right.id));
}
Upvotes: 2
Reputation: 1682
First, you should sort each objects places lists, then sort the main/date list.
Attempting to sort both at once might cause random results
Upvotes: 0