Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq To SQL Group By and Sum

Tags:

linq-to-sql

Her is an image showing a the table i have, b the grid i need to display. opps cant post image. ill try to explain. My table have four colums.

  1. Project Number(String)
  2. ItemNumber(String)
  3. Location(String)
  4. Qty.(Real).

My grid need to look like this.

  1. ProjectNumber
  2. ItemNumber
  3. QtyMain.
  4. QtyOther.

I Need to write a linq query Grouping evry line so i will se 1 Line pr Project/ItemNumber combination summing qty into 2 differetn colums 1 showing to qty where location is main and 1 showing the qty where location is not (!=) main. Can linq do this for me, or how can thsi be done?

like image 994
Jes Gudiksen Avatar asked Dec 19 '11 13:12

Jes Gudiksen


1 Answers

public class Foo
{
    public Int32 ProjectNumber;
    public String ItemNumber;
    public String InventLocation;
    public Int32 Qty;
}

void Main()
{
    List<Foo> foos = new List<Foo>(new[]{
        new Foo { ProjectNumber = 1, ItemNumber = "a", InventLocation = "Main", Qty = 3 },
        new Foo { ProjectNumber = 1, ItemNumber = "a", InventLocation = "Main", Qty = 3 },
        new Foo { ProjectNumber = 1, ItemNumber = "a", InventLocation = "Sub", Qty = 2 },
        new Foo { ProjectNumber = 1, ItemNumber = "a", InventLocation = "Sub", Qty = 1 },
        new Foo { ProjectNumber = 1, ItemNumber = "a", InventLocation = "Sub2", Qty = 5 }
    });

    var foo = from f in foos
              group f by new { f.ProjectNumber, f.ItemNumber } into fGroup
              select new {
                ProjectNumber = fGroup.Key.ProjectNumber,
                ItemNumber = fGroup.Key.ItemNumber,
                QtyMain = fGroup.Where (g => g.InventLocation == "Main").Sum (g => g.Qty),
                Rest = fGroup.Where (g => g.InventLocation != "Main").Sum (g => g.Qty)
              };
    foo.Dump();
}

Resulting in:

IEnumerable<> (1 item)  
ProjectNumber ItemNumber QtyMain Rest 
1             a          6       8
like image 96
Brad Christie Avatar answered Sep 29 '22 17:09

Brad Christie