Question

I have a list of anonymous objects as:

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

how can I find the "Job2" using linq?

e.g.

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

I am aware of the below but cannot apply it to my use case above in an elegant way:

var anonymJob = new 
                {
                  JobName = "Job2",
                  JobDate = "Date2",
                  JobUser = "User2"
                };

dynamic tJob = anonymJob.GetType();
string jobName = tJob.JobName; // this will be "Job2"

Please note jobs.First() or Last() are not accepted as correct answers to this question is how to find a job based on its specific properties.

Thanks

Was it helpful?

Solution

If you're working within the same method, you can just use a list of the anonymous type:

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

The use of the implicitly typed array allows your list to still be strongly typed, but using the anonymous type.

If you must use a List<object>, then I'd expect:

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

to work. Note that this doesn't involve copying the list or changing the declaration type of the list at all. You could also use:

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

OTHER TIPS

You can use dynamic in your query:

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

Make it a List<dynamic> instead of List<object>.

Then you can use the normal LINQ queries.

Use List<dynamic> instead of List<object>.

Paste this in to LINQPad to see:

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top