C
C#2y ago
Dropps

❔ simplification

iam wondering if there is a way to simplify following example for readability using linq
object outerobject = new();
object apiData = new();
foreach (ObjectX x in apiData.Keys)
{
foreach (List<ObjectY> yList in apiData.Values)
{
outerobject.Components.Add(new Components
{
property = x,
propertyList = x
});
}
}
object outerobject = new();
object apiData = new();
foreach (ObjectX x in apiData.Keys)
{
foreach (List<ObjectY> yList in apiData.Values)
{
outerobject.Components.Add(new Components
{
property = x,
propertyList = x
});
}
}
9 Replies
Dropps
DroppsOP2y ago
i have around 120 properties in the true thing but cant share due to it being sensitive data
ero
ero2y ago
yList is never used?
Dropps
DroppsOP2y ago
oh the second property is supposed to be yList
ero
ero2y ago
some kinda zip probably? actually apiData is a dictionary, no?
HimmDawg
HimmDawg2y ago
Just asking: Do you really want to add each combination of keys and values? Because like that, you are combining each key with all values
Dropps
DroppsOP2y ago
its a dict<dict<string, int>, dict<JsonElement, List<object>>> yes thats supposed to happen
HimmDawg
HimmDawg2y ago
Aight Not sure if there's much to simplify tho. This is readable enough imo. However you could use
apiData.Keys.SelectMany(k => apiData.Values.Select(v => (k, v)));
apiData.Keys.SelectMany(k => apiData.Values.Select(v => (k, v)));
Since this is nothing else than computing the cartesian product, you could write a function CartesianProduct that computes the combinations. I cannot think of anything else rn fluffyFoxThink
Dropps
DroppsOP2y ago
worked perfectly thanks a lot
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server