使用IComparer按另一个列表使用自定义对象对列表进行排序

Tom*_*nig 5 .net c# interface list icomparer

我的问题是关于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);
    }
}
Run Code Online (Sandbox Code Playgroud)

一些数据可以使用:

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, "?")
};
Run Code Online (Sandbox Code Playgroud)

并且具有正确顺序的列表:

List<int> OrderByList = new List<int>() { 78, 4, 63, 7, 12, 2 };
Run Code Online (Sandbox Code Playgroud)

所以,现在我怎么能知道IComparer通过排序OrderByList?我真的不知道怎么做,我知道linq会很容易,但我没有机会使用它.

Jam*_*iec 5

您的代码目前存在一些错误。如果您查看文档,IComparer<T>您会发现这T就是您要比较的内容。在您的代码中,这是Test但您继续编写代码以进行比较What- 这意味着您的代码将无法编译。请参阅此处- 错误消息是:

'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));
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其用于订购:

 WhatList.Sort(new WhatComparer(OrderByList));
Run Code Online (Sandbox Code Playgroud)

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