【问题标题】:Sort list based on another? [duplicate]基于另一个排序列表? [复制]
【发布时间】:2016-09-28 11:36:33
【问题描述】:

我有两个通用列表,存储了两种不同的类型:

class A {
    public int id;
    //...
}
class B {
    public int id;
    //...
}

他们有一个相似的属性,id。现在第一个列表具有一定的对象及其 ID 顺序,而第二个列表具有完全不同的 ID 顺序:

List<A> listA; // the ids of objects inside go as follows: 4, 5, 1
List<B> listB; // the ids of objects inside go as follows: 1, 4, 5

我想对 listB 进行排序,以便 listB[0].id==listA[0].idlistB[1].id==listA[1].id 等。考虑过使用 Join,但不知道在 OrderBy 中添加什么。

【问题讨论】:

  • 你为什么不创建一个带有ID的类Mother,让你的两个类继承它然后按它排序?
  • listB[1].id==listA[2].id 不应该是listB[1].id==listA[1].id 吗?
  • @Nasreddine 是的,已修复,谢谢
  • 另外,当ListA 有一个带有Id 的项目在ListB 中不存在时会发生什么?例如,您不能只从ListB[1] 转到ListB[4],因此您应该只使用OrderBy(x =&gt; x.id) 两个列表。

标签: c# linq


【解决方案1】:

您可以临时创建包含所需索引的匿名对象,然后按此索引排序:

var result = listB.Select((b, index) => 
                     new {Index = listA.FindIndex(a => a.id == b.id),
                          B = b})
                  .OrderBy(b => b.Index)
                  .Select(b => b.B).ToList();

所以第一个Select 创建了一个对象序列,其中包含listA 中匹配元素的Index
然后这个序列按该索引排序,最后的Select 以正确的顺序给出来自listB 的实例。

【讨论】:

    【解决方案2】:

    只需逐项迭代List&lt;A&gt;,在List&lt;B&gt; 的源实例中找到对应的B 项并将其存储到另一个List&lt;B&gt; 的目标实例中。你就完成了。

    List<B> destinationListB = new List<B>();
    foreach (A in listA)
    {
        B b = listB.FirstOrDefault(item => item.id = A.id);
        if (b != nul) destinationListB.Add(b);
    }
    

    免责声明:可能有更省时的解决方案。

    【讨论】:

      【解决方案3】:

      List.FindIndex()是你的朋友:

      var orderedB = listB.OrderBy(b => listA.FindIndex(a => a.id == b.id));
      

      工作示例:https://dotnetfiddle.net/CpLeFU

      【讨论】:

        猜你喜欢
        • 2011-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-26
        • 1970-01-01
        • 2019-04-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多