【问题标题】:Sorting a nested list array in C#在 C# 中对嵌套列表数组进行排序
【发布时间】:2016-02-07 22:12:32
【问题描述】:

我正在尝试对 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 =&gt; e.UserId.Equals(userId)).OrderBy(q =&gt; q.id).Include("date.place").ToList();

我意识到,日期对象中的地点不是根据 place_Id 在排序数组中提取的,而是随机提取的。有没有办法可以拉出按顺序排列的播放列表? .OrderBy(q => q.id) 只会拉取播放列表的有序列表,而不是嵌套对象。

【问题讨论】:

  • 所以你需要一个按两个字段(places.places_id、playlist.id)的顺序排列的列表吗?

标签: c# asp.net arrays sorting


【解决方案1】:

您可以在客户端的嵌套列表中排列项目的顺序:

// 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));
}

【讨论】:

  • 效果很好。我实际上期待有一些事情可以在没有嵌套 for 循环的情况下在一行中完成,但这看起来很棒!
【解决方案2】:

首先,您应该对每个对象地点列表进行排序,然后对主/日期列表进行排序。

尝试同时排序可能会导致随机结果

【讨论】:

  • 我想这是我的问题。我将如何对地点列表进行排序?我会先建立列表然后重新保存到播放列表中吗?一些代码可能会有所帮助,谢谢
猜你喜欢
  • 2013-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-06
相关资源
最近更新 更多