C
C#2y ago
Salty

❔ Iteration over multiple objects at the same time

How do I iterate through several objects at the same time. Supposedly the objects have the same properties and I want to concat obj1.prop1 + obj2.prop1, obj1.prop2+obj2.prop2 etc etc
21 Replies
Pobiega
Pobiega2y ago
.Zip list1.Zip(list2).Select(...) should do roughly that
Salty
SaltyOP2y ago
what if i have 100 lists
Pobiega
Pobiega2y ago
use a for loop also, why do you have 100 lists 😄
Salty
SaltyOP2y ago
well its 100 objects, each is sorta like a data set image them as replicates of an experiment i want to stitch same properties from each object together
Pobiega
Pobiega2y ago
right. I'd personally do that by putting all your objects into an array, then use Aggregate on that array Its fine thinker, you dont have to delete 😄
Salty
SaltyOP2y ago
aggregate, alright ill look into it wheres my chatgpt...
Thinker
Thinker2y ago
check the docs
Pobiega
Pobiega2y ago
Enumerable.Aggregate Method (System.Linq)
Applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value, and the specified function is used to select the result value.
Pobiega
Pobiega2y ago
check the examples here
Thinker
Thinker2y ago
Essentially
lists.Aggregate((a, b) =>
new Thing(
a.A + b.A,
a.B + b.B,
/*etc.*/));
lists.Aggregate((a, b) =>
new Thing(
a.A + b.A,
a.B + b.B,
/*etc.*/));
Pobiega
Pobiega2y ago
the actual method definition is hard to read
Salty
SaltyOP2y ago
ill take a look
Topend
Topend2y ago
this is correct, Thing() can be object or function, and this will save on total ops
Thinker
Thinker2y ago
?
Salty
SaltyOP2y ago
what is "lists" list of lists?
Pobiega
Pobiega2y ago
no its the list of things your "data sets"
Salty
SaltyOP2y ago
i have a list of x objects or just x objects
Pobiega
Pobiega2y ago
you'll need them to be enumerable, so you need to stick them in an array or something
Salty
SaltyOP2y ago
thats not a problem
Pobiega
Pobiega2y ago
example:
var datasets = Enumerable.Range(0, 100).Select(_ => Dataset.Create()).ToArray();

var aggregateDataset = datasets.Aggregate((a, b) =>
{
a.A += b.A;
a.B += b.B;
a.C += b.C;
return a;
});

Console.WriteLine(aggregateDataset);
var datasets = Enumerable.Range(0, 100).Select(_ => Dataset.Create()).ToArray();

var aggregateDataset = datasets.Aggregate((a, b) =>
{
a.A += b.A;
a.B += b.B;
a.C += b.C;
return a;
});

Console.WriteLine(aggregateDataset);
the top line just creates 100 randomized "datasets"
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