How to use LINQ with dynamic collections

C#Linq

C# Problem Overview


Is there a way to convert dynamic object to IEnumerable Type to filter collection with property.

dynamic data = JsonConvert.DeserializeObject(response.Content);

I need to access something like this

var a = data.Where(p => p.verified == true)

Any Ideas?

C# Solutions


Solution 1 - C#

So long as data is an IEnumerable of some kind, you can use:

var a = ((IEnumerable) data).Cast<dynamic>()
                            .Where(p => p.verified);

The Cast<dynamic>() is to end up with an IEnumerable<dynamic> so that the type of the parameter to the lambda expression is also dynamic.

Solution 2 - C#

Try casting to IEnumerable<dynamic>

((IEnumerable<dynamic>)data).Where(d => d.Id == 1);

This approach is 4x faster than other approachs.

good luck

Solution 3 - C#

If you are able to, the ideal solution is to specify the type when deserializing, so to avoid having to cast later. This is a lot cleaner than the approaches suggested above.

So if you have -

dynamic data = JsonConvert.DeserializeObject(response.Content);

Then simply change this to -

var data = JsonConvert.DeserializeObject<IEnumerable<dynamic>>(response.Content);

Solution 4 - C#

This might help, replace jsonString with response.Content and use nested loops if required based on your response content.

In the below code JValue.Parse will return JToken which is IEnumerable

        string jsonString = "[{\"Question\":{\"QuestionId\":49,\"QuestionText\":\"Whats your name?\",\"Answer\":\"xyz\"}},{\"Question\":{\"QuestionId\":51,\"QuestionText\":\"Are you smart?\",\"Answer\":\"Yes\"}}]";
        dynamic myObject = JValue.Parse(jsonString);
        foreach (dynamic questions in myObject)
        {
            Console.WriteLine(questions.Question.QuestionId + "." + questions.Question.QuestionText.ToString());
            Console.WriteLine("Ans. " +questions.Question.Answer);
            Console.WriteLine();
        }
        Console.Read();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1618825View Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#Yaser MoradiView Answer on Stackoverflow
Solution 3 - C#user3407039View Answer on Stackoverflow
Solution 4 - C#VarunView Answer on Stackoverflow