将List <object>转换为类

时间:2016-09-26 06:47:19

标签: c# linq

我有三节课:

<li role="presentation" data-toggle="tab" ng-class="{active: activetab == 'list'}"><a href="#list">list</a></li>
<li role="presentation" data-toggle="tab" ng-class="{active: activetab == 'add'}"><a href="#add">add</a></li>
<li role="presentation" data-toggle="tab" ng-class="{active: activetab == 'search'}"><a href="#search">search</a></li>

一个实例public class MyClass { public Head Head { get; set; } public List<Car> Cars { get; set; } } public class Head { public int Id { get; set; } } public class Car { public string Color { get; set; } public bool Active { get; set; } }

List<object>

我想将我的实例转换为我的类List<object> o = new List<object>() { new Head() { Id = 1 }, new Car() { Color = "Yellow", Active = false }, new Car() { Color = "Black", Active = true }, new Car() { Color = "White", Active = false } }; 的实例(第一个索引=属性我的类MyClass的头部和所有Car =属性列表

最好的方法是什么?

1 个答案:

答案 0 :(得分:4)

Linq将在这里帮助你。 使用OfType扩展方法获取特定类型的实例。

new MyClass{
   Head = o.OfType<Head>().First(),
   Cars = o.OfType<Car>().ToList()
}