将类类型的列表分配给对象类型列表

时间:2014-08-20 06:34:49

标签: c#

我有一个列表如下:

IList<Employee> emp = new List<Employee>
            {
                new Employee() {Id=1, Name = "A", Age = 20,  Address = "X"},
                new Employee() {Id=2, Name = "B", Age = 21,  Address = "Y"},
                new Employee() {Id=3, Name = "C", Age = 22,  Address = "Z"},

            };

和另一个清单:IList<Object> emp2=new List<Object>(); 如果我想将emp分配给emp2,例如:emp2=emp;我该怎么做?

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

foreach (var employee in emp)
{
    emp2.Add(employee);
}

答案 1 :(得分:1)

我会这样做:

List<Employee> emp = //insert initialization code here
IList<object> emp2 = emp.OrderBy(e => e.WhicheverPropertyYouWantToSortBy).Cast<object>().ToList();