列表>>自己的比较器

发布于 2024-08-26 01:39:09 字数 227 浏览 4 评论 0原文

我有一个列表,其中元素是:

struct element { 
                double priority; 
                int value; 
               }

如何实现自己的比较器,允许我按优先级对列表进行排序?我尝试使用 SortredList...但它不允许重复的键:(

非常感谢您的帮助!

I have a List where element is:

struct element { 
                double priority; 
                int value; 
               }

How can I implement my own comparer which allow me sort List by priority ? I try with SortredList... but it don't allow douplicated keys :(

Big thanks for help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

笑,眼淚并存 2024-09-02 01:39:09

假设 C# 3 或更高版本:

var sorted = MyList.OrderBy(e => e.priority);

Assuming C# 3 or later:

var sorted = MyList.OrderBy(e => e.priority);
聆听风音 2024-09-02 01:39:09

您可以使用 Sort 执行就地排序需要比较的重载 delegate:

yourList.Sort((x, y) => x.priority.CompareTo(y.priority));

对于旧版本的 C#,您需要将 lambda 替换为老式的 delegate 语法:

yourList.Sort(
    delegate(element x, element y) { return x.priority.CompareTo(y.priority); });

You can perform an in-place sort by using the Sort overload that takes a Comparison<T> delegate:

yourList.Sort((x, y) => x.priority.CompareTo(y.priority));

For older versions of C# you'll need to swap out the lambda for old-school delegate syntax:

yourList.Sort(
    delegate(element x, element y) { return x.priority.CompareTo(y.priority); });
隱形的亼 2024-09-02 01:39:09

如果您不能依赖 C# 3 扩展或 Lambda,那么您可以让您的结构实现 IComparable 界面,如下所示:

struct element : IComparable
{
    double priority;
    int value;
    public element(int val, double prio)
    {
        priority = prio;
        value = val;
    }
    #region IComparable Members

    public int CompareTo(object obj)
    {
        // throws exception if type is wrong
        element other = (element)obj;
        return priority.CompareTo(other.priority);
    }

    #endregion
}

还有一个 此接口的类型安全版本,但原理是相同的

在结构或类上实现该接口后,调用 Sort List 方法将“正常工作”

static void Main(string[] args)
{
    Random r = new Random();
    List<element> myList = new List<element>();
    for (int i = 0; i < 10; i++)
        myList.Add(new element(r.Next(), r.NextDouble()));
    // List is now unsorted 
    myList.Sort();
    // List is now sorted by priority
    Console.ReadLine();
}

If you can't rely on C# 3 extensions or Lambdas then you can have your struct implement the IComparable interface, like so:

struct element : IComparable
{
    double priority;
    int value;
    public element(int val, double prio)
    {
        priority = prio;
        value = val;
    }
    #region IComparable Members

    public int CompareTo(object obj)
    {
        // throws exception if type is wrong
        element other = (element)obj;
        return priority.CompareTo(other.priority);
    }

    #endregion
}

There are also a typesafe version of this interface, but the principle is the same

After you have that interface implemented on your struct or class, calling the Sort method on List<> will "just work"

static void Main(string[] args)
{
    Random r = new Random();
    List<element> myList = new List<element>();
    for (int i = 0; i < 10; i++)
        myList.Add(new element(r.Next(), r.NextDouble()));
    // List is now unsorted 
    myList.Sort();
    // List is now sorted by priority
    Console.ReadLine();
}
神爱温柔 2024-09-02 01:39:09

这取决于您是否想要对列表本身进行排序,或者按排序顺序检索值(而不更改列表)。

对列表本身进行排序(假设您有一个名为 elementsList):

elements.Sort((x, y) => x.priority.CompareTo(y.priority));
// now elements is sorted

.NET 2.0 等效项:

elements.Sort(
    delegate(element x, element y) {
        return x.priority.CompareTo(y.priority);
    }
);

要按排序顺序获取值:

var orderedElements = elements.OrderBy(x => x.priority);
// elements remains the same, but orderedElements will retrieve them in order

中没有 LINQ 等效项.NET 2.0,但您可以编写自己的:

public static IEnumerable<T> OrderBy<T>(IEnumerable<T> source, Comparison<T> comparison) {
    List<T> copy = new List<T>(source);
    copy.Sort(comparison);

    foreach (T item in copy)
        yield return item;
}

用法:

Comparison<element> compareByPriority = delegate(element x, element y) {
    return x.priority.CompareTo(y.priority);
};

// unfortunately .NET 2.0 doesn't support extension methods, so this has to be
// expressed as a regular static method
IEnumerable<element> orderedElements = OrderBy(elements, compareByPriority);

This depends on if you want to sort the list itself, or retrieve the values in sorted order (without changing the list).

To sort the list itself (supposing you have a List<element> called elements):

elements.Sort((x, y) => x.priority.CompareTo(y.priority));
// now elements is sorted

.NET 2.0 equivalent:

elements.Sort(
    delegate(element x, element y) {
        return x.priority.CompareTo(y.priority);
    }
);

To get the values in sorted order:

var orderedElements = elements.OrderBy(x => x.priority);
// elements remains the same, but orderedElements will retrieve them in order

There's no LINQ equivalent in .NET 2.0, but you can write your own:

public static IEnumerable<T> OrderBy<T>(IEnumerable<T> source, Comparison<T> comparison) {
    List<T> copy = new List<T>(source);
    copy.Sort(comparison);

    foreach (T item in copy)
        yield return item;
}

Usage:

Comparison<element> compareByPriority = delegate(element x, element y) {
    return x.priority.CompareTo(y.priority);
};

// unfortunately .NET 2.0 doesn't support extension methods, so this has to be
// expressed as a regular static method
IEnumerable<element> orderedElements = OrderBy(elements, compareByPriority);
眼前雾蒙蒙 2024-09-02 01:39:09

如果你想对列表本身进行排序而不创建新实例,你可以实现
IComparer,然后使用您的实现实例调用 List.Sort

public class ElementComparer : IComparer<element>
{
    public int Compare(element x, element y)
    {
        throw new NotImplementedException();
    }
}

If you want to sort the list itself without creating a new instance, you can implement
IComparer, then call List.Sort with an instance of your implementation

public class ElementComparer : IComparer<element>
{
    public int Compare(element x, element y)
    {
        throw new NotImplementedException();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文