I have DTOs like this
public class Obj1
{
public string a1 { get; set; };
public Obj2[] a2 { get; set; };
}
public class Obj2
{
public string b1 { get; set; };
public Obj3[] b2 { get; set; };
}
public class Obj3
{
public string Key { get; set; };
}
So, the object will be like
Obj1 o = new Obj1
{
a1="a";
a2=new[]
{
new Obj2
{
b1="b";
b2=new[]
{
new Obj3
{
Key="c";
}
}
}
}
}
I have Obj1. How can I group it in the form of dictionary of type
IDictionary<string, IEnumerable<Obj2>>
where Key is in Obj3.
I tried using GroupBy but did not get the relevant result.
CodePudding user response:
If I understand the end goal - co combine all Obj2
by all child Obj3.Key
and after fixing the code to make it compile you can use SelectMany
into intermediate data structure with aggregation with GroupBy
:
var dictionary = o.a2
.SelectMany(o2 => o2.b3.Select(o3 => (o3.Key, o2)))
.GroupBy(t => t.Key)
.ToDictionary(g => g.Key, g => g.ToList());
CodePudding user response:
Im not quite sure, but your class "obj2" instead of having 2 properties, you can make it with one property of Dictionary with a string key and Ienumerable value, so your variable could look like this. Dictionary<string, Dictionary<string, Ienumerable>> and you can add "obj3" as a value or key.