LINQ aggregate and group by specified intervals | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

LINQ aggregate and group by specified intervals

I'm trying to understand how LINQ can be used to group data by specific intervals, and then ideally aggregate each group. For example, I have a class called sample: public class Sample { public int value; public double count; } These observations are contained as a series in a List collection: List<Sample> series; group value by specified period (ex period =10) and then aggregate count by sum

20th Nov 2020, 4:00 PM
hossein B
hossein B - avatar
5 Answers
+ 8
hossein B Based on your description, I'm imagining the code would look something like this: var query = from item in series group item by item.Period into p where p.Key == 10 select new { Period = p.Key, Sum = p.Sum(i => i.Value) }; foreach(var i in query) { Console.WriteLine(
quot;Period: {i.Period} | Sum: {i.Sum}"); } ---- I've created this working sample code to give you a starting point with some sample data. https://code.sololearn.com/cCQ7SfOcAL1Q/?ref=app
21st Nov 2020, 6:24 AM
David Carroll
David Carroll - avatar
+ 8
You've lost me in your example. Where is period in your Sample class? It would be better if you created some code as a starting point with the sample data to review and work with. Also... what does grouping by period represent?
21st Nov 2020, 5:37 AM
David Carroll
David Carroll - avatar
+ 5
David Carroll thanks 😍 You never cease to amaze me. I have been looking for an answer since yesterday. I felt frustrated. I got the idea from your code and what I searched on Google. Finally it became clear to me. 😎 This is the result of my efforts and your guidance https://code.sololearn.com/ckf5vkeHrt82/?ref=app
21st Nov 2020, 9:47 AM
hossein B
hossein B - avatar
+ 2
hossein B Awesome! I'm glad I could help. 🍻 Personally... it was refreshing to answer a question that was a little more involved than the typical questions I'm seeing here these days. 😉👌 So... thanks for taking it up a notch. 🙏
21st Nov 2020, 1:10 PM
David Carroll
David Carroll - avatar
0
Good
30th Nov 2020, 8:56 PM
AMAN DHIMAN
AMAN DHIMAN - avatar