【问题标题】:How to sort an array of objects (classes)? [duplicate]如何对对象(类)数组进行排序? [复制]
【发布时间】:2022-01-20 00:00:28
【问题描述】:

我正在尝试使用Array.Sort 对对象数组进行排序,但得到了 InvalidOperationException。正如我所读到的,我正在尝试对一个复杂的对象进行排序,我需要使用 IComparable <T> 比较接口,但我不明白它是如何工作的。

这是我的代码:

     public class C
     {
         public int I { get; set; }
     }

     static void Main(string[] args)
     {
         C[] classes = new C[100000];
         Random rand = new Random();
         for (int i = 0; i < 100000; i++)
         {
            classes[i] = new C { I = rand.Next(1, 100000) };
         }
     
         Array.Sort<C>(classes); // Here I get an exception
     }

【问题讨论】:

  • 只需在您的 C 类上实现接口 IComparable 即可。没什么太花哨或复杂的。您可以让智能感知完成所有工作,并在 CompareTo 方法中写下有关如何进行实际比较的逻辑。
  • 欢迎来到 Stack Overflow。 “我需要使用 IComparable 比较接口,但我不明白它是如何工作的。”那么,您是否阅读过IComparable&lt;T&gt; 的文档?您是否尝试将c# sorting tutorialc# icomparable tutorial 放入搜索引擎?请阅读meta.stackoverflow.com/questions/261592
  • 从根本上说,你必须回答的问题是:“给定两个Cs,说哪个'更小'的规则是什么?”该语言不会在这里猜测您的意图。您必须编写实现该规则的代码。您使用该接口来表示您的代码正在实现该规则。

标签: c# arrays class sorting


【解决方案1】:

你应该向 .Net解释如何比较类:

...
// having a and b instances we should compare I properties
Array.Sort<C>(classes, (a, b) => a.I.CompareTo(b.I)); 
...

或者你可以让class C可比(以便Array.Sort&lt;C&gt;(classes);开始工作):

public class C : IComparable<C> {
  public int I { get; set; }

  public int CompareTo(C other) {
    if (null == other)
      return 1;

    return I.CompareTo(other.I);  
  }
}

【讨论】:

    猜你喜欢
    • 2020-05-18
    • 2013-02-24
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多