0

I need to cast JArray which I received from browser to list of MyType object. The problem is that I don't want to use .ToObject<> extension because object sended from browser can have missing or extra values and I cannot change deserializer. I wrote my own parser to receive data from single JObject. Usage:

foreach (var _object in _jarray)
{
    using (var tp = new TokenParser(_object)) 
    {
        MyType test = new MyType() 
        {
            id = tp.ConvertToInt("token_key")
        };
    }
}

What I want to do is something like this

_jarray.ForEach(_object => {
    using (var tp = new TokenParser(_object)) 
    {
        MyType test = new MyType() 
        {
            id = tp.ConvertToInt("token_key")
        };
    }
});

I don't want to cast elements like:

_jarray.Select(x => 
    (int)["token_key"]
);

I tried to wrote this extension based on LINQ equivalent of foreach for IEnumerable<T> but it seems that Action requires T as parameter type. I don't need this because JArray is an array of JObject.

Is this possible to achieve?

Community
  • 1
  • 1
Adam Mrozek
  • 1,410
  • 4
  • 26
  • 49
  • `_jarray.ToList().ForEach(...)`? – Ilya Chumakov Apr 28 '16 at 14:21
  • That extension method should just work, but [per the docs](http://www.newtonsoft.com/json/help/html/t_newtonsoft_json_linq_jarray.htm) `JArray` is `IEnumerable`, not `IEnumerable` as you claim. – Charles Mager Apr 28 '16 at 14:21
  • Why can't you do something like : `var result = _jarray.Select(o => { var tp = ...; return new MyType() { id = tp.ConvertToInt("token_key") }; });` – Fabjan Apr 28 '16 at 14:24

0 Answers0