.net - new - linq to sql group by sum




按多列分組 (8)

我如何在LINQ中做GroupBy多列

在SQL中與此類似的東西:

SELECT * FROM <TableName> GROUP BY <Column1>,<Column2>

我如何將其轉換為LINQ:

QuantityBreakdown
(
    MaterialID int,
    ProductID int,
    Quantity float
)

INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity)
SELECT MaterialID, ProductID, SUM(Quantity)
FROM @Transactions
GROUP BY MaterialID, ProductID

.GroupBy(x => (x.MaterialID, x.ProductID))


使用匿名類型。

例如

group x by new { x.Column1, x.Column2 }

您也可以使用Tuple <>進行強類型分組。

from grouping in list.GroupBy(x => new Tuple<string,string,string>(x.Person.LastName,x.Person.FirstName,x.Person.MiddleName))
select new SummaryItem
{
    LastName = grouping.Key.Item1,
    FirstName = grouping.Key.Item2,
    MiddleName = grouping.Key.Item3,
    DayCount = grouping.Count(), 
    AmountBilled = grouping.Sum(x => x.Rate),
}

確定這是:

var query = (from t in Transactions
             group t by new {t.MaterialID, t.ProductID}
             into grp
                    select new
                    {
                        grp.Key.MaterialID,
                        grp.Key.ProductID,
                        Quantity = grp.Sum(t => t.Quantity)
                    }).ToList();

組x由新{x.Col,x.Col}


自C#7以來,您也可以使用值元組:

group x by (x.Column1, x.Column2)

要么

.GroupBy(x => (x.Column1, x.Column2))

需要注意的是,您需要為Lambda表達式發送對象,並且不能為類使用實例。

例:

public class Key
{
    public string Prop1 { get; set; }

    public string Prop2 { get; set; }
}

這將編譯,但每個週期會生成一個密鑰

var groupedCycles = cycles.GroupBy(x => new Key
{ 
  Prop1 = x.Column1, 
  Prop2 = x.Column2 
})

如果你不想命名關鍵屬性然後檢索它們,你可以這樣做。 這將GroupBy正確,並給你的關鍵屬性。

var groupedCycles = cycles.GroupBy(x => new 
{ 
  Prop1 = x.Column1, 
  Prop2= x.Column2 
})

foreach (var groupedCycle in groupedCycles)
{
    var key = new Key();
    key.Prop1 = groupedCycle.Key.Prop1;
    key.Prop2 = groupedCycle.Key.Prop2;
}

.GroupBy(x => x.Column1 + " " + x.Column2)




aggregate