Home > Software design >  LINQ Group by multiple conditions
LINQ Group by multiple conditions

Time:12-26

I have dataset like below. Data of scripts is getting downloaded real time.

enter image description here

Below tasks I want to acheive.

  1. Separate the rows by different scripts

  2. Group the rows by minute

  3. Sum the total buyers and total sellers for that minute

  4. Subtract the volume of last row of the current minute with the last row of the previous minute.

The sample result looks like below: enter image description here

I started writing LINQ group by, but unable to get the final result.

Please guide how to achieve this.

var dataHere = _context.MyScriptDatas.GroupBy(g => g.Script);

I understand I will have to write multiple queries but unable to understand the sequence. Please help.

CodePudding user response:

Try this

.GroupBy(x => new { x.Column1, x.Column2 })

CodePudding user response:

The first two points look to me like they can by done together. You want to group the data by both script and minute. This could be done by using something like this:

var data = _context.MyScriptDatas.GroupBy(g => new {g.Script, g.DateTime.Minute});

After grouping the data, you can start doing operations on them. If you want to select and sum, you can try something like this:

data.Select(g =>
   new
   {
       TotalBuyers = g.Sum(x => x.TotalBuyers)
   })

As for the last point, it is quite similar to the one above. Someone asked something like this here, check it out: Calculate difference from previous item in a group with (single) LINQ query

Good luck!

  • Related