BillPull
BillPull

Reputation: 7013

C# Linq Convert Object Property to Array

I have an object that I am converting to JSON to be consumed by Ember.js. Currently I have some child objects that are fully expanded but ember expects just an array of ids on the client side. How can I flatten the object out to be a int[]

items = Mapper.Map<IList<Item>>(client.GetItems());
foreach (var item in items)
{
  int[] choices = item.Choices.Select(x => x.Id).ToArray();

  item.Choices = choices;
}

get an error about not being able to convert to type int[] from IList<Item> how can I cast the property?

example current JSON I produce after serializing

{ "items": [
   {
     "id": 0,
     "name": "Item0",
     "description": "...",
     "choices": [
       { "id": 0, "property": "somevalue" },
       { "id": 1, "property": "somevalue" },
     ]
   },
   {
     "id": 1,
     "name": "Item1",
     "description": "...",
     "choices": [
       { "id": 0, "property": "somevalue" },
       { "id": 1, "property": "somevalue" },
     ]
   }
]}

The JSON I would like to produce

{ "items": [
   {
     "id": 0,
     "name": "Item0",
     "description": "...",
     "choices": [0, 1]
   },
   {
     "id": 1,
     "name": "Item1",
     "description": "...",
     "choices": [0, 1]
   }
]}

Upvotes: 2

Views: 2704

Answers (2)

Poornima
Poornima

Reputation: 928

get an error about not being able to convert to type int[] from IList how can I cast the property?

You cannot cast one type to another. Instead you can create another property of type int[] in your class and use the LINQ statement in getter (with necessary validation checks).

public int[] ChoiceIDs
{ 
    get {
     return this.Choices.Select(x => x.Id).ToArray();
    }
}

Upvotes: 1

Konstantin
Konstantin

Reputation: 3294

SelectMany flattens List of Lists and produces single List with all items.

items.SelectMany(x=>x.Choices.Select(y=>y.Id).ToArray()));

Upvotes: 4

Related Questions