【问题标题】:Sorting List with Custom object by another List using IComparer使用 IComparer 通过另一个列表对具有自定义对象的列表进行排序
【发布时间】:2012-12-13 12:04:37
【问题描述】:

我的问题是关于IComparer 接口,我以前从未使用过它,所以希望您能帮助我正确设置所有内容。

我必须使用接口按照另一个List<int> 的确切顺序对自己的对象列表进行排序。 我在网上找不到任何对这个问题有用的东西,我发现的都是 linq 语句,我不能使用。

示例代码如下:

public class What : IComparer<What>
{
    public int ID { get; set; }
    public string Ever { get; set; }

    public What(int x_ID, string x_Ever)
    {
        ID = x_ID;
        Ever = x_Ever;
    }

    public int Compare(What x, What y)
    {
        return x.ID.CompareTo(y.ID);
    }
}

需要处理的一些数据:

List<What> WhatList = new List<What>()
{
    new What(4, "there"),
    new What(7, "are"), 
    new What(2, "doing"),
    new What(12, "you"),
    new What(78, "Hey"),
    new What(63, "?")
};

以及顺序正确的列表:

List<int> OrderByList = new List<int>() { 78, 4, 63, 7, 12, 2 };

那么现在我如何告诉IComparerOrderByList 排序? 我真的不知道该怎么做,我知道使用 linq 会很容易,但我没有机会使用它。

【问题讨论】:

  • 出于兴趣,为什么没有 LINQ?
  • 是否可以假设所有ID 值都存在于您的OrderBylist 集中?

标签: c# .net list interface icomparer


【解决方案1】:

您的代码目前存在一些问题。如果您查看docs for IComparer&lt;T&gt;,您会发现T 就是您要比较的内容。在您的代码中,这是Test,但您继续编写代码以比较What - 这意味着您的代码将无法编译。请参阅here - 错误消息是:

'Rextester.What' 没有实现接口成员'System.Collections.Generic.IComparer.Compare(Rextester.Test, Rextester.Test)'
(忽略那里的“Rextester”位!)。

说了这么多,你应该实现一个WhatComparer

public class WhatComparer : IComparer<What>
{
    private List<int> orderBy;
    public WhatComparer(List<int> orderBy)
    {
        this.orderBy = orderBy;
    }

    public int Compare(What x, What y)
    {
        return orderBy.IndexOf(x.ID).CompareTo(orderBy.IndexOf(y.ID));
    }
}

然后用它来订购:

 WhatList.Sort(new WhatComparer(OrderByList));

现场示例:http://rextester.com/BZKO33641

【讨论】:

  • 谢谢!正是我需要的!
【解决方案2】:

您应该创建另一个类来进行比较,并给出所需的顺序:

public class OrderComparer : IComparer<What>
{
    private readonly Dictionary<int, int> idIndexes = new Dictionary<int, int>();
    public OrderComparer(List<int> idOrders)
    {
        for(int i = 0; i < idOrders.Length; i++)
        {
            idIndexes[idOrders[i].ID] = i;
        }
    }

    public int Compare(What x, What y)
    {
        return idOrders[x.ID].Compare(idOrders[y.ID]);
    }
}

那么你可以这样做:

WhatList.Sort(new OrderComparer(OrderByList));

【讨论】:

    【解决方案3】:

    最简单的方法是使用自定义Comparison&lt;T&gt;

    WhatList.Sort((x, y) =>
    {
        return OrderByList.IndexOf(x.ID).CompareTo(orderByList.IndexOf(y.ID));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 2015-01-08
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      相关资源
      最近更新 更多