How to use LINQ with dynamic collections

后端 未结 3 1998
小鲜肉
小鲜肉 2020-12-04 11:10

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

dynamic data = JsonConvert.Deseri         


        
相关标签:
3条回答
  • 2020-12-04 11:43

    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);
    
    0 讨论(0)
  • 2020-12-04 11:54

    Try casting to IEnumerable<dynamic>

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

    This approach is 4x faster than other approachs.

    good luck

    0 讨论(0)
  • 2020-12-04 11:58

    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.

    0 讨论(0)
提交回复
热议问题