如果两个列表有不同的类型,我如何合并?

时间:2015-11-24 20:42:42

标签: c#

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

这是我要合并的两个列表,但我无法弄清楚它们是如何组合的。

2 个答案:

答案 0 :(得分:5)

从公共基类派生它们然后你会使用类似

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

或..将它们转换为公共基类:) object

答案 1 :(得分:-1)

另一种选择:创建一个包含公共属性的类

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