Home > Software design >  How to sort property from multiple objects
How to sort property from multiple objects

Time:10-08

I have some objects. And in each object there is a propety age. And I want to sort the property age of all the objects. And in this case I have two objects. But for example if you have three, four..etc objects. Maybe there is a more generic method for this?

So this is the code:

List<Person> personList = new List<Person>
{

    new Person { Age = 77 },
    new Person { Age = 88 },
    new Person { Age = 1001 },
    new Person { Age = 755 }
};

List<Dog> Dogist = new List<Dog>
{

    new Dog { Age = 1 },
    new Dog { Age = 9 },
    new Dog { Age = 10 },
    new Dog { Age = 8 }
};

personList.Sort((x, y) => x.Age.CompareTo(y.Age));
Dogist.Sort((x, y) => x.Age.CompareTo(y.Age));

So the output has to be in this case:

1 8 9 10 77 88 755 1001

CodePudding user response:

You could create two lists of the ages which will create an IEnumerable<int>, and Combine and Order them...

var personAsAge = personList.Select(p => p.Age);
var dogAsAge = Dogist.Select(d => d.Age);

var ageOrder = personAsAge.Concat(dogAsAge).OrderBy(a => a);

You will need to import System.Linq; too.

CodePudding user response:

In addition to Christian's approach of mutating / extending an existing list with Concat, it's also possible to do this without materializing the projections and using Union to produce a new combined sequence, before ordering, like so:

var sortedAges = personList
    .Select(p => p.Age)
    .Union(dogList.Select(d => d.Age))
    .OrderBy(age => age);
  • Related