How can I merge two lists when they have different types?

var orderedStudents = students.OrderBy(x => x.FacultyNumber).ToList();
var orderedWorkers = workers.OrderByDescending(x => x.moneyPerHour).ToList();

Those are the two lists that I want to merge, but I can't figure out how since they have different types.

Upvotes: 1

Views: 221

Answers (2)

KiwiPiet
KiwiPiet

Reputation: 1324

Another option : Create a class that contains the common properties

class Person {
    public string Name { get; set; }
    public string Lastname { get; set; }
}

var orderedStudents = students.OrderBy(x => x.FacultyNumber).Select(x => new Person { Name = x.Name, Lastname = x.Lastname});
var orderedWorkers = workers.OrderByDescending(x => x.moneyPerHour).Select(x => new Person { Name = x.Name, Lastname = x.Lastname});
var mergedList = orderedStudents.Concat(orderedWorkers).ToList();

Upvotes: -1

steavy
steavy

Reputation: 1576

Either derive them from common base class and then you would use sth like

var humanBeings = orderedStudents.Cast<Human>().Concat(orderedWorkers.Cast<Human>()).ToList();

or .. cast them to common base class :) object

Upvotes: 5

Related Questions