在c#中查找匿名对象列表中的项

本文关键字:列表 对象 查找 | 更新日期: 2023-09-27 18:13:14

我有一个匿名对象列表:

var jobs = new List<object>
               {
                 new
                 {
                   JobName = "Job1",
                   JobDate = "Date1",
                   JobUser = "User1"
                 },
                 new
                 {
                   JobName = "Job2",
                   JobDate = "Date2",
                   JobUser = "User2"
                 }
               };

如何使用linq找到"Job2"?

var job2 = jobs.Where(x=>x.JobName == "Job2");

我知道下面的情况,但不能以一种优雅的方式将它应用到上面的用例中:

var anonymJob = new 
                {
                  JobName = "Job2",
                  JobDate = "Date2",
                  JobUser = "User2"
                };
dynamic tJob = anonymJob.GetType();
string jobName = tJob.JobName; // this will be "Job2"

请注意job . first()或Last()不被接受,因为这个问题的正确答案是如何根据job的特定属性找到job。

谢谢

在c#中查找匿名对象列表中的项

如果您在同一方法中工作,则可以使用匿名类型的列表:

var jobs = new [] {
    new { JobName = "Job1", JobDate = "Date1", JobUser = "User1" },
    new { JobName = "Job2", JobDate = "Date2", JobUser = "User2" }
}.ToList();
var job2 = jobs.First(x => x.JobName == "Job2");

使用隐式类型数组允许你的列表仍然是强类型的,但是使用匿名类型。

如果你必须使用List<object>,那么我希望:

IEnumerable<dynamic> dynamicJobs = jobs;
var job2 = dynamicJobs.First(x => x.JobName == "Job2");

工作。注意,这根本不涉及复制列表或更改列表的声明类型。你也可以使用:

var job2 = jobs.Cast<dynamic>().First(x => x.JobName == "Job2");

您可以在查询中使用dynamic:

var job2 = jobs.Where(x => ((dynamic)x).JobName == "Job2");

List<object>改为List<dynamic>

List<dynamic>代替List<object>

粘贴到LINQPad查看:

var jobs = new List<dynamic>
               {
                 new
                 {
                   JobName = "Job1",
                   JobDate = "Date1",
                   JobUser = "User1"
                 },
                 new
                 {
                   JobName = "Job2",
                   JobDate = "Date2",
                   JobUser = "User2"
                 }
               };
jobs.Where(x=>x.JobName == "Job2").Dump();