Home > OS >  Reading a List<(string,string[])> from appsettings.json
Reading a List<(string,string[])> from appsettings.json

Time:10-08

I need to read "Products" to a List<(string,string[])> variable. appsettings.json:

{
  "Products": [
    {"fruits":["apple","cherry","tomato"]},
    {"vegetables":["carrot","tomato"]}
  ]
}

Note: Please presuppose that I cannot change this appsettings.json entry format. But the variable could also be an array of ValueTuple instead of a List of ValueTuple. ValueTuple format must be (string category,string[] items).

Thanks to @Serge for the great answer ! I'm sure I'm not alone struggling with linq and that config file.

CodePudding user response:

try this

 var products = Configuration
 .GetSection("Products")
 .Get<Dictionary<string, string[]>[]>()
 .SelectMany(i => i)
 .Select(i => new Tuple<string, string[]>(i.Key, i.Value)) // or you can convert here to any class
 .ToList();
  • Related