【问题标题】:How to sort array of objects by fields without linq and other classes? (in C#)如何在没有 linq 和其他类的情况下按字段对对象数组进行排序? (在 C# 中)
【发布时间】:2018-08-01 04:56:31
【问题描述】:

这里是如何按字段对对象数组进行排序的示例。我需要创建能够做同样事情的函数,但 WITHOUT Linq、Generic 或任何其他类。

p.s 您可以在 Test 类中添加方法来比较字段。

using System;
using System.Linq;

class Test {
    public int Count;
    public int Sum;
}

class Program {
    static void Main() {
        Test a1 = new Test() {
            Count = 1 ,
            Sum = 20
        };
        Test a2 = new Test() {
            Count = 2 ,
            Sum = 10
        };
        Test a3 = new Test() {
            Count = 3 ,
            Sum = 30
        };

        var arr = new Test[] { a1, a2, a3};

        var result = arr.OrderBy(n => n.Count).ToList();

        foreach (var item in result) {
            Console.WriteLine(item.Count);
        }
    }

    static void MyOrder() {
        //function which will sort passed array of objects by fields
    }
}

【问题讨论】:

标签: c# arrays linq sorting object


【解决方案1】:

一种方法是使用Array.Sort() 静态方法。但是如果你想使用它,你的类必须实现IComparable接口,例如:

class Test : IComparable
{
  public int Count;
  public int Sum;

  public int CompareTo(object obj)
  {
    if (!(obj is Test))
      throw new ArgumentException("You can't compare two objects of different types!");

    var test = (Test)obj;
    if (test.Count < this.Count) return 1;
    else if (test.Count > this.Count) return -1;
    else return 0;
  }
}

然后代码会变成:

var arr = new Test[] { a1, a3, a2 };
Array.Sort(arr);

编辑:

如果你想在运行时改变排序字段,你可以使用IComparer接口如下:

public class Test
{
  public int Count;
  public int Sum;
}

public class TestComparerBySum : IComparer<Test>
{
  public int Compare(Test x, Test y)
  {
    if (x.Sum > y.Sum) return 1;
    else if (x.Sum < y.Sum) return -1;
    else return 0;
  }
}

public class TestComparerByCount : IComparer<Test>
{
  public int Compare(Test x, Test y)
  {
    if (x.Count > y.Count) return 1;
    else if (x.Count < y.Count) return -1;
    else return 0;
  }
}

并在这样的代码中使用它:

var arr = new Test[] { a3, a2, a1 };

Array.Sort(arr, new TestComparerBySum());

Array.Sort(arr, new TestComparerByCount());

【讨论】:

  • 如果我想按 Count 排序怎么办?或者我需要同时使用它们?
  • @LukaMamulaishvili 用Count比较,看看CompareTo的方法!试一试,你会发现它的对比如你所愿。
  • 对不起,我的意思是总和。我可以同时使用它们吗?
  • @LukaMamulaishvili 如果要使用Sum,则在CompareTo 方法中将所有Count 更改为Sum。 “我可以同时使用它们吗?”是什么意思? ??
  • @LukaMamulaishvili 是的,您的要求是不明确传递排序字段,因此您需要以某种方式让编译器知道要比较什么!唯一的方法是编写代码。所以,是的,每次改变主意都需要更改代码,没有办法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-01
  • 2014-11-13
  • 1970-01-01
  • 2019-06-04
  • 2020-06-28
  • 2017-10-06
  • 2019-02-17
相关资源
最近更新 更多