在 C# 中对嵌套列表数组进行排序
本文关键字:数组 排序 列表 嵌套 | 更新日期: 2023-09-27 18:33:33
我正在尝试对 asp.net 中的嵌套元素数组进行排序,但遇到了一些麻烦。目前我有一个播放列表,它的模型如下:
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; }
}
}`
如您所见,它是一个嵌套的对象数组,日期,以及另一个对象数组,地点。
我现在正在做的是提取数据如下:
playlist = db.Playlists.Where(e => e.UserId.Equals(userId)).OrderBy(q => q.id).Include("date.place").ToList();
我意识到的是,日期对象中的位置不是根据place_Id在排序数组中拉出的,而是随机的。有没有办法让我拉出播放列表并订购位置?这。OrderBy(q => q.id) 只会拉取播放列表的有序列表,而不是嵌套对象。
您可以在客户端上排列嵌套列表中的项顺序:
// 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));
}
首先,您应该对每个对象的位置列表进行排序,然后对主/日期列表进行排序。
尝试同时对两者进行排序可能会导致随机结果