简体   繁体   中英

Count minus Count in GroupBy in Linq

I have a question, for which I need suggestions regarding: I got ONE table(CurrentItems) with columns: Id, ChangedTime, Status, ItemType, Company

The Status column contains a number where 1 means Added and 3 means Removed
I need to count the totalnumber of Items in a certain point of time for a certain company. Any itemtype can be added multiple times.

Example table contains:

1. Company A add(1) Item 1 at 2001-01-01
2. Company B add(1) Item 1 at 2001-02-01
3. Company A removes(3) Item 1 at 2001-03-01
4. Company B add(1) Item 1 at 2001-04-01
5. Company B removes(3) Item 1 at 2001-05-01
6. Company A add(1) Item 1 at 2001-06-01
7. Company A add(1) Item 1 at 2001-07-01
8. Company B removes(3) Item 1 at 2001-08-01

If I look at 2001-05- 02 then the result should be

Company A totalitems on date: 0
Company B totalitems on date: 1

If I look at 2001-08- 02 the the result should be

Company A totalitems on date: 2
Company B totalitems on date: 0

The solution would be nice to have in a lambda statement if its possible.

How far did I get?

 CurrentItems.Where(o=> (o.Status==1 || Status==3) && o.UpdatedTime <
     DateTime.Parse("2001-08-02") &&o.Company="A").GroupBy(z=>z.Status)
     .Select(z=> new
     {
     Name=z.Key, 
     Summa=z.Count(),
     }
...

If I perform this in SQL I would use two select's and substract one from another, but I think it is possible to write it in a more compact way in LINQ.

You can do something like this:

 CurrentItems.Where(o=> o.UpdatedTime < DateTime.Parse("2001-08-02")
   .GroupBy(z=>z.Company)
   .Select(z=> new
   {
       Name=z.Key, 
       Summa=z.Where(i => i.Status == 1).Count() - z.Where(i => i.Status == 3).Count()
   });

It will give you the sum for each company.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM