0

Iam using the ServiceStack.Text JsonObject parser to map into my domain model. I basically have anthing working, except when using Linq to filter on ArrayObject and the try to convert it using convertAll. Iam cannot come arround actuall after using link, adding element by element to an JsonArrayObjects list and then pass it.

var tmpList = x.Object("references").ArrayObjects("image").Where(y => y.Get<int>("type") != 1).ToList();
JsonArrayObjects tmpStorage = new JsonArrayObjects();
foreach (var pic in tmpList) {
    tmpStorage.Add(pic);
}
if (tmpStorage.Count > 0) {
    GalleryPictures = tmpStorage.ConvertAll(RestJsonToModelMapper.jsonToImage);
}

Question: Is there a more elegant way to get from IEnumarable back to JsonArrayObjects? Casting will not work, since where copys elements into a list, instead of manipulating the old one, therefor the result is not an downcasted JsonArrayObjects, rather a new List object.

Best

emx
  • 45
  • 7

2 Answers2

1

Considering this more elegant is arguable, but I would probably do:

var tmpStorage = new JsonArrayObjects();
tmpList.ForEach(pic => tmpStorage.Add(RestJsonToModelMapper.jsonToImage(pic)));

And if this kind of conversion is used frequently, you may create an extension method:

public static JsonArrayObjects ToJsonArrayObjects(this IEnumerable<JsonObject> pics)
{
    var tmpStorage = new JsonArrayObjects();

    foreach(var pic in pics)
    {
        tmpStorage.Add(RestJsonToModelMapper.jsonToImage(pic));
    }

    return tmpStorage;
}

This way you would end up with simpler consumer code:

var tmpStorage = x.Object("references")
                  .ArrayObjects("image")
                  .Where(y => y.Get<int>("type") != 1)
                  .ToJsonArrayObjects();
jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
1

Like this?

var pictures = x.Object("references")
     .ArrayObjects("image")
     .Where(y => y.Get<int>("type") != 1)
     .Select(RestJsonToModelMapper.JsonToImage)
     .ToList();
Alexey Zimarev
  • 17,944
  • 2
  • 55
  • 83