Reputation: 43
How to convert Dictionary<string, List<object>>
to List<Dictionary<string, object>
in LINQ? I am doing it using for loop, any way to do it in a compact way?
Dictionary<string, List<object>> mydata = new Dictionary<string, List<object>>();
List<object> ldate=new List<object>(){"1/1/2000","1,1/2001"};
List<object> lage=new List<object>(){"4","5"};
mydata["date"] = ldate;
mydata["age"] = lage;
List<Dictionary<string, object>> mytarget = new List<Dictionary<string, object>>();
Dictionary<string,object> t1=new Dictionary<string,object>();
Dictionary<string,object> t2=new Dictionary<string,object>();
t1["date"]="1/1/2000";
t1["age"]="4";
t2["date"]="1/1/2001";
t2["age"]="5";
mytarget.Add(t1);
mytarget.Add(t2);
many thanks, canric
Upvotes: 4
Views: 1211
Reputation: 17064
I'll just give you simpler alternative without the tricky usage of aggregate:
var target = Enumerable.Range(0, source.Values.First().Count)
.Select(i => source.ToDictionary(x => x.Key, x => x.Value[i]))
.ToList();
Upvotes: 0
Reputation: 726579
This should work:
Dictionary<string,List<object>> orig = ...
var res = Enumerable.Range(0, orig.Values.First().Count)
.Select(
i => orig.Aggregate(
new Dictionary<string,object>()
, (d, p) => { d[p.Key] = p.Value[i]; return d; }
)
).ToList();
See a demo on ideone.
Upvotes: 1