Linq To SQL Group By和Sum

时间:2011-12-19 13:58:18

标签: linq-to-sql

她是一张显示我所拥有的桌子的图片,b我需要显示的网格。 opps无法发布图片。我试着解释一下。我的桌子有四个柱子。

  1. 项目编号(字符串)
  2. ItemNumber(字符串)
  3. 位置(字符串)
  4. 数量。(真实)。
  5. 我的网格需要看起来像这样。

    1. ProjectNumber
    2. ItemNumber
    3. QtyMain。
    4. QtyOther。
    5. 我需要写一个linq查询分组evry line所以我将se 1行pr项目/ ItemNumber组合求和qty到2个不同的colums 1显示qty where location is main和1显示qty where location not not(!= )主要。 linq可以为我做这个,或者怎么办?

1 个答案:

答案 0 :(得分:8)

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();
}

导致:

IEnumerable<> (1 item)  
ProjectNumber ItemNumber QtyMain Rest 
1             a          6       8