-5

Here is example of how to sort array of objects by it's fields. I need to create function which will do same thing but WITHOUT Linq, Generics or any other classes.

p.s You can add methods in Test class to compare fields.

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
    }
}
  • 4
    I didn't downvote but I think the reason is that you have not demonstrated any code that you have even attempted. This is not a code writing service. – JohanP Aug 01 '18 at 05:06
  • Possible duplicate of [How to sort array of FileInfo objects in descending order without LINQ](https://stackoverflow.com/questions/15135508/how-to-sort-array-of-fileinfo-objects-in-descending-order-without-linq) – Richardissimo Aug 01 '18 at 05:17
  • Perhaps take a look at https://en.wikipedia.org/wiki/Sorting_algorithm. That should be a very good place to start. – Enigmativity Aug 01 '18 at 07:06

1 Answers1

0

One method is to use Array.Sort() static method. But if you want to use it, you class must implement IComparable interface, for example:

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;
  }
}

And then code would become:

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

EDIT:

If you want to change ordering field at runtime, you can use IComparer interface as folloing:

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;
  }
}

And use it in code like this:

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

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

Array.Sort(arr, new TestComparerByCount());
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69