How to flatten nested dictionaries in a class using LINQ
The closest solution to what I was looking for is this thread How to flatten nested objects with linq expression
But I am getting error when trying this approach
The type arguments for the 'System.Linq.Enumerable.SelectMany (System.Collections.Generic.IEnumerable, System.Func>)' method cannot be deprecated. Try to specify type arguments explicitly.
My code:
var aa = t.data.SelectMany(x =>
x.Value.innerData.SelectMany(y => new { /*Error at this SelectMany*/
url = x.Key,
disp = x.Value.disp,
date = y.Key,
count = y.Value.count,
rank = y.Value.rank,
}));
My classes:
public class TData {
public Dictionary<string, TDetail> data { get; set; }
}
public class TDetail {
public string disp { get; set; }
[Newtonsoft.Json.JsonProperty("data")]
public Dictionary<string, Metrics> innerData { get; set; }
}
public class Metrics {
public string count { get; set; }
public string rank { get; set; }
}
The JSON I receive from the third party API looks like this:
{
"data": {
"abc.com": {
"disp": "#712176",
"data": {
"2015-02-08": {
"count": 4,
"rank": 5.8
},
"2015-02-23": {
"count": 3,
"rank": 8.3
},
"2015-03-14": {
"count": 5,
"rank": 3.7
}
}
},
"nbc.com": {
"disp": "#822176",
"data": {
"2015-02-08": {
"count": 3,
"rank": 5.5
},
"2015-02-23": {
"count": 5,
"rank": 8.4
},
"2015-03-14": {
"count": 7,
"rank": 4.7
}
}
}
}
}
How can I explicitly specify the type arguments in this case? Thank.
source to share
SelectMany
projects each individual element into a sequence of elements (and then aligns it). Your outer SelectMany
projects each element into a sequence, but your inner SelectMany
projects each element onto separate elements that are not sequences. If you want to project every element in sequence into one element, you need to use Select
instead of SelectMany
.
source to share