mightycode Newton
mightycode Newton

Reputation: 3949

How to sort property from multiple objects

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> dogList = 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));
dogList.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

Upvotes: 1

Views: 91

Answers (2)

StuartLC
StuartLC

Reputation: 107237

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

foreach (var age in sortedAges) // << The result is only 'materialized' here, once.
{ ...

Upvotes: 3

Christian Phillips
Christian Phillips

Reputation: 18749

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.

Upvotes: 2

Related Questions