0

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.

1
  • so you need a list ordered by two fields (places.places_id , playlist.id) in that order? Commented Feb 7, 2016 at 22:38

2 Answers 2

2

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));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great that worked perfectly. I was actually expecting there to be a something that could be done in a single line without the nested for loops, but this looks great!
0

First, you should sort each objects places lists, then sort the main/date list.

Attempting to sort both at once might cause random results

1 Comment

I guess that is my question. how would I sort the places lists? Would I be building the list first then resaving into the playlist? Some code may be helpful, Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.