ChakirBelhaj
ChakirBelhaj

Reputation: 305

foreach and index in .ToDictionary C#

I am web-scraping some data and trying to write the scraped data to a json file using C# newtonsoft.Json

I get stuck when writing a foreach in my .ToDictionary function as well as not being able to ++ an index into my .ToDictionary function.

My class:

public class JsonParametersData
{
    public bool required { get; set; }
    public bool list { get; set; }
    public List<string> options { get; set; }
}

My arrays

var jsonData              = new List<Dictionary<string, Dictionary<string, JsonParametersData>>>();
var moduleParameters      = new List<string>();
var parameterOptionsArray = new List<List<string>>();
var parameterOptions      = new List<string>();
var requiredArray         = new List<bool>();
var listArray             = new List<bool>();
string moduleName         = item.Attributes["href"].Value.Replace("_module.html", "");

The code which is commented shows what I am trying to do.

int index = 0;
jsonData.Add(new Dictionary<string, Dictionary<string, JsonParametersData>>()
{
    {
        moduleName,
        moduleParameters
            .ToDictionary(n => n,
                n => new JsonParametersData
                {
                    required = requiredArray[index],
                    list = listArray[index],
                    options = new List<string>() { "option1", "option2" },
                   /*
                    foreach (var parameteroption in parameterOptionsArray[index])
                    {
                        options.Add(parameteroption);
                    }
                    index++;
                    */
                })
    }
});

string json = JsonConvert.SerializeObject(jsonData.ToArray());

//write string to file
System.IO.File.WriteAllText(@"path", json);

Upvotes: 1

Views: 328

Answers (3)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

As I´ve written in the comments you can make only assignments in an object-initializer. Thus the following is allowed:

var a = new { MyMember = anInstance }

whilst this is not:

var a = new { MyMember = anInstance, anInstance.DoSomething() };

That´s one of those cases where you should not use Linq at all, as it leads to more confusion than it helps. Instead use a good old-styled loop:

int index = 0;
var innerDict = new Dictionary<string, JsonParametersData>();

foreach(var name in moduleParameters)
{
    innerDict[name] = new JsonParametersData
                {
                    required = requiredArray[index],
                    list = listArray[index],
                    options = new List<string>() { "option1", "option2" },
                } 
    innerDict[name].Options.AddRange(parameterOptionsArray[index]);
    index++;
}

var dict = new Dictionary<string, Dictionary<string, JsonParametersData>>();
dict[moduleName] = innerDict;
jsonData.Add(dict);
string json = JsonConvert.SerializeObject(jsonData.ToArray());

Upvotes: 1

danish
danish

Reputation: 5610

You appear to have a jagged array in parameterOptionsArray. You can make use of SelectMany here. Perhaps following sample can help:

    string[][] parameterOptionsArray = new string[2][];
    parameterOptionsArray[0] = new string[2];
    parameterOptionsArray[0][0] = "1";
    parameterOptionsArray[0][1] = "2";
    parameterOptionsArray[1] = new string[2];
    parameterOptionsArray[1][0] = "3";
    parameterOptionsArray[1][1] = "4";

    var testing = new {options = parameterOptionsArray.SelectMany(x => x).ToList()};        
    testing.options.ForEach(x => Console.WriteLine(x));

Upvotes: 1

MikkaRin
MikkaRin

Reputation: 3084

Your parameterOptionsArray is not an Array, but a List of lists.

The thing is that parameterOptionsArray[index] is a List, not a string. So you should use AddRange() instead of Add().

parameterOptionsArray.Foreach(parameteroption => options.AddRange(parameteroption));

Upvotes: 2

Related Questions