0

So I have this problem. I have Project class with Name and Resource properties. I have DataSet and I want to set my Resource property values(of type Dictionary) from the DataSet. And tha's where I struggle.

Any ideas how I could solve this problem? Preferably not using LINQ/Lambdas. I'm getting Invalid Initializer member declarator error. I hope there is a proper way to do it so error is not relevant. Thanks in advance!

public class FakeDataset
{    
    public static System.Data.DataTable TTable()
    {
        DataTable table = new DataTable("Resources");
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Resource", typeof(string));
        table.Columns.Add("Value", typeof(string));            

        table.Rows.Add("Project", "Resource1", "11");
        table.Rows.Add("Project", "Resource2", "12");
        table.Rows.Add("Project", "Resource3", "9");
        table.Rows.Add("Project22", "Resource1", "1");
        table.Rows.Add("Project22", "Resource2", "2");
        return table;
    }

    public static DataSet CreateDataset()
    {            
        DataSet dataset = new DataSet("ProjectDataset");            
        dataset.Tables.Add(TTable());
        return dataset;
    }
}   

public class Project
{
    public string Name { get; set; }
    public Dictionary<string, string> Resource { get; set; }
}

class Program
{
    public static void Main()
    {
        var dataset = FakeDataset.CreateDataset();
        var projectList = new List<Project>();

        foreach (DataTable table in dataset.Tables)
        {                
            foreach (DataRow dataRow in table.Rows)
            {
                projectList.Add(new Project { Name = Convert.ToString(dataRow["Name"]), Resource.Add(dataRow["Resource"].ToString(), dataRow["Value"].ToString()) });
            }
        }            
    }
}
Arghya C
  • 9,805
  • 2
  • 47
  • 66
Paul
  • 169
  • 13

1 Answers1

0

Writing your for loop like this will solve the issue

foreach (DataTable table in dataset.Tables)
{
    foreach (DataRow dataRow in table.Rows)
    {
        var dict = new Dictionary<string, string>();
        dict.Add(dataRow["Resource"].ToString(), dataRow["Value"].ToString());
        projectList.Add(new Project { Name = Convert.ToString(dataRow["Name"]), Resource = dict });
    }
} 

Or, using collection initialize syntax

foreach (DataTable table in dataset.Tables)
{
    foreach (DataRow dataRow in table.Rows)
    {
        projectList.Add(new Project { 
            Name = Convert.ToString(dataRow["Name"]), 
            Resource = new Dictionary<string, string> { { dataRow["Resource"].ToString(), dataRow["Value"].ToString() } } }
        );
    }
} 

But, do you really need Resource as a Dictionary<,> ? As of now, it will contain only one entry per Project class. Maybe you just need two string properties instead?

Arghya C
  • 9,805
  • 2
  • 47
  • 66