1

I created model like this (in separate file MMproducts.cs inside project):

public class Product
{
    public string sku { get; set; }
}

public class Order
{
    public int id { get; set; }
    public List<Product> products { get; set; }
}

public class Root
{
    public string status { get; set; }
    public List<Order> orders { get; set; }
}

How to Console.WriteLine all Products sku?

This model translate json data. To access to 'first' level of list i used:

MMproducts mmResponse = JsonConvert.DeserializeObject<MMproducts> (response.Content);
foreach (var defindex in mmResponse.orders) { }

but i don't know how to use this metod to print sku.

Michal
  • 85
  • 9
  • 1
    Are you looking for the [`foreach`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in) keyword or the [`SelectMany`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.selectmany?view=net-5.0) method? – D M May 18 '21 at 21:50
  • 3
    Does this answer your question? [Iterating through a list of lists?](https://stackoverflow.com/questions/1771845/iterating-through-a-list-of-lists) – D M May 18 '21 at 21:50
  • 1
    You probably want `var skus = root.orders.SelectMany(o => o.products.Select(p => p.sku)).ToArray();`. Side note: stick to the [standard conventions](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions) of identifiers (tl;dr: Use PascalCase for the names of your properties). – 41686d6564 stands w. Palestine May 18 '21 at 21:55

2 Answers2

2

SelectMany will get you a zipped list of products, then you can select skus from there:

foreach (var sku in mmResponse.orders.SelectMany(o => o.products).Select(p => p.sku))
{
    Console.WriteLine(sku);
}
umberto-petrov
  • 731
  • 4
  • 8
0

Try using a reference to the List variable name. E.G:

//Assuming Root r, Orders r[0-9] and Products r.[0-9].[0-9] already exist
for(int i=0 ; i< r.orders.Length ;i++){
   for(int f=0 ;f< r.orders[i].products.Length;f++){
      Console.WriteLine("SKU is "+r.orders[i].products[f]);
   }
}
StarshipladDev
  • 1,166
  • 4
  • 17