【问题标题】:In C#, how can I sort a collection of objects by a seperate int array?在 C# 中,如何通过单独的 int 数组对对象集合进行排序?
【发布时间】:2014-04-23 17:15:24
【问题描述】:

我有一个 Person 对象的集合,而 Person 对象有一个 id 属性。

 var peopleList = new List<Person>();
 peopleList .Add(new Person(){Name = Joe, Id = 30};
 peopleList .Add(new Person(){Name = Tom, Id = 22};
 peopleList .Add(new Person(){Name = Jack, Id = 62};

我现在有一个整数数组,表示我想要显示数组的顺序

 var list = new List<int>();
 list.Add(22);
 list.Add(62);
 list.Add(30);

List 数组对 PeopleList 集合进行排序的正确方法是什么?所以我得到了一个订单:

Tom, Jack, Joe

【问题讨论】:

    标签: c# sorting collections


    【解决方案1】:

    创建人员对象的 id 查找:

    var peopleLookup = peopleList.ToDictionary(person => person.Id);
    

    然后您可以浏览您的 ID 列表,将每个 ID 映射到一个人:

    var query = list.Select(id => peopleLookup[id]);
    

    【讨论】:

    • +1。请注意,如果您有重复的 Id(不太可能基于文件名),您需要手动转换为字典而不是 ToDictionary
    • @AlexeiLevenkov 在这种情况下,ID 应该是唯一的似乎很清楚,除非有任何其他明确的要求,否则我期望它会引发异常。如果 id 不是唯一的,那么我想解决方案是首先删除重复项,然后使用这个确切的代码。
    【解决方案2】:

    您可以使用list.IndexOf(Id)。使用 LINQ 的 OrderBy 创建一个新列表

    var sorted = peopleList.OrderBy(x => list.IndexOf(x.Id)).ToList();
    

    或使用List&lt;T&gt;.Sort 重新排序列表本身

    peopleList.Sort((x, y) => list.IndexOf(x.Id).CompareTo(list.IndexOf(y.Id)));
    

    【讨论】:

    • 您的第二个解决方案是 O(n^2 * log(n)),对于可以在 O(n) 时间内轻松解决的问题。
    • 是的,先制作字典可以改善这一点,但你的答案更好,所以我没有费心改进我的。
    【解决方案3】:

    如果收集量很大,可能会很慢,但这是可行的。

    var peopleList = new List<Person>();
    peopleList.Add(new Person() { Name = "Joe", Id = 30 });
    peopleList.Add(new Person() { Name = "Tom", Id = 22 });
    peopleList.Add(new Person() { Name = "Jack", Id = 62 });
    
    var list = new List<int>();
    list.Add(22);
    list.Add(62);
    list.Add(30);
    
    peopleList.Sort((x, y) => list.IndexOf(x.Id).CompareTo(list.IndexOf(y.Id)));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-26
      • 2022-12-11
      • 2017-11-01
      • 2016-07-12
      • 1970-01-01
      相关资源
      最近更新 更多