2

I want to sort list of class objects.

class tocka
{
Point t;
double kut;
int redkotiranja;

public tocka(Point _t, double _kut, int _redkotiranja)
{
t = _t;
kut = _kut;
redkotiranja = _redkotiranja;
}
}

Here is the list:

List<tocka> tocke= new List<tocka>();
tocka a = new tocka(new Point(0, 1), 10, 1);
tocke.Add(a);
tocka b = new tocka(new Point(5, 1), 10, 1);
tocke.Add(b);
tocka c = new tocka(new Point(2, 1), 10, 1);
tocke.Add(c);
tocka d = new tocka(new Point(1, 1), 10, 1);
tocke.Add(d);
tocka ee = new tocka(new Point(9, 1), 10, 1);
tocke.Add(ee);

I want to sort list tocke by t.X

How I do that in C#?

0

5 Answers 5

3

Using LINQ:

tocke = tocke.OrderBy(x=> x.t.X).ToList();

Make t public.

1

Direct solution without LINQ (just list sorting, no additional list creation).

Providing that t is made public:

  tocke.Sort((left, right) => left.t.X - right.t.X); 

But the best way, IMHO, is to make class tocka comparable:

class tocka: IComparable<tocka> {
  ...

  public int Compare(tocka other) {
    if (Object.RefrenceEquals(other, this))
      return 0;
    else if (Object.RefrenceEquals(other, null))
      return 1;

    return t.X - other.t.X; // <- Matthew Watson's idea
  }
}

// So you can sort the list by Sort:

tocke.Sort();
1
  • +1 for providing an answer that doesn't copy the list into another collection, sort it, then copy it back into another list - thus avoiding a bad case of LINQitis. ;) BTW I think you can simplify the comparison by just returning (other.t.X - t.X) since the value only needs to be +ve, -ve or 0. Dec 12, 2013 at 8:38
0

You can use LINQ, for instance like this:

tocke.Sort( (x,y) => x.t.X.CompareTo(y.t.X) );

but first you have to make t public, at least when getting it:

public Point t { get; private set; }
0
  • First of all you should add the public modifier to your class.
  • Second you should refactor your fields to properties. It is suggested to expose properties to the public than fields.

Then the solution would be as follwos

public class Tocka
{
    public Point Point { get; private set; }
}

As answer to your question you shall use Linq

List<Tocka> l = ...
var orderedTocka = l.OrderBy(i => i.Point.X);

Note: Just be sure that Point is never null, otherwise the Linq-Query listed above won't work

0

You can sort in-place using:

tocke.Sort((a, b) => a.t.X.CompareTo(b.t.X));

Or using LINQ (creates a new list):

tocke = tocke.OrderBy(x=> x.t.X).ToList();

You should probably encapsulate t as a property. Also, if t can be null, you should add nullity checks to the above lambdas.

Not the answer you're looking for? Browse other questions tagged or ask your own question.