使用LINQ for List of type object

A1R*_*ack 1 c# linq

我有一个类型对象列表

List<object> _list;
Run Code Online (Sandbox Code Playgroud)

我在一个方法中初始化这个列表,并添加一些属性的项目

void CreateList()
{
_list= new List<object>();
_list.Add(new {Prop1 = 45, Prop2 = "foo", Prop3 = 4.5});
_list.Add(new {Prop1 = 14, Prop2 = "bar", Prop3 = 3.1});
}
Run Code Online (Sandbox Code Playgroud)

但是我现在有一个类型对象的列表,我不知道它的类型或元素的类型.

我想根据列表中的属性使用LINQ选择一些元素,例如FindAll().我该怎么做?创建POCO课程会更好吗?

das*_*ght 7

我现在有一个类型对象列表,我不知道它的类型或元素的类型.

这就是你object用作元素类型的方法.您仍有多种选择:

  • 如果您可以创建一个表示列表项的类,则问题就解决了
  • 如果您可以在使用它的相同上下文中创建List,则可以使用var捕获匿名类型
  • 如果您没有这些选项,请转换为dynamic静态类型检查并放弃

第二个选项看起来像这样:

var list = (new[] {
    new {Prop1 = 45, Prop2 = "foo", Prop3 = 4.5}
,   new {Prop1 = 14, Prop2 = "bar", Prop3 = 3.1}
}).ToList();
...
var filtered = list.Where(x => x.Prop1==45).ToList();
Run Code Online (Sandbox Code Playgroud)

第三个选项看起来像这样:

var filtered = _list
    .Cast<dynamic>()
    .Where(x => x.Prop1==45) // <<== No static type checking here
    .Cast<object>()
    .ToList();
Run Code Online (Sandbox Code Playgroud)