Thor Thor - 1 year ago 101
C# Question

Converting a list of dictionaries to models

I have a

containing a
Dictionary<string, string>
that represents lines from a database from multiple joined tables. I have tried all sorts of LINQ approaches but I always hit a wall where LINQ just doesn't allow certain operations on this data structure. I have tried to simplify the code example as much as I think I can without misrepresenting the core issue so...

How can I extract explicit
from a
inside of a
and put it into a

I need a scale-able solution where the
could do the same with the subData.

public class Program
public static void Main(string[] args)
List<Dictionary<string, string>> data = GetData();
data.Add(new Dictionary<string, string>() { ["modelData"] = "Bob", ["subModelData"] = "Frank" });
data.Add(new Dictionary<string, string>() { ["modelData"] = "Nancy", ["subModelData"] = "Boy" });
List<Model> models = new List<Model>();
//Fails in this linq statement. Anonymous types don't allow key accessors
foreach (Dictionary<string, string> distinctModel in data.GroupBy(x => new { x["dataKey"] }))
List<Dictionary<string, string>> newModelData = data.Where(d => d["data1Key"] == distinctModel["dataKey"]).ToList();
Model newModel = new Model(newModelData);

public class Model
public string modelData;
public List<Dictionary<string, string>> subData;

public Model(List<Dictionary<string, string>> data) {
modelData = data[0]["dataKey"];
subData = data;

Answer Source

Anonymous type projection initializer should be a name. So I think you need to add an explicit name:

data.GroupBy(x => new {S = x["dataKey"] })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download