Gruppo Di più colonne
Domanda
Come posso fare GroupBy più colonne in LINQ
Qualcosa di simile a questo in SQL:
SELECT * FROM <TableName> GROUP BY <Column1>,<Column2>
Come posso convertire questo a 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
Soluzione
Utilizzare un tipo anonimo.
Esempio
group x by new { x.Column1, x.Column2 }
Altri suggerimenti
campione procedurale
.GroupBy(x => new { x.Column1, x.Column2 })
Ok ottenuto questo come:
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();
Per il gruppo da più colonne, Prova a modificare la ...
GroupBy(x=> new { x.Column1, x.Column2 }, (key, group) => new
{
Key1 = key.Column1,
Key2 = key.Column2,
Result = group.ToList()
});
Allo stesso modo è possibile aggiungere Colonna3, column4 etc.
Dato che C # 7 è anche possibile utilizzare le tuple di valore:
group x by (x.Column1, x.Column2)
o
.GroupBy(x => (x.Column1, x.Column2))
Si può anche usare una tupla <> per un raggruppamento fortemente tipizzato.
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),
}
Anche se questa domanda sta chiedendo su gruppo da proprietà di classe, se si desidera raggruppare base a più colonne contro un oggetto ADO (come un DataTable), è necessario assegnare i "nuovi" elementi da variabili:
EnumerableRowCollection<DataRow> ClientProfiles = CurrentProfiles.AsEnumerable()
.Where(x => CheckProfileTypes.Contains(x.Field<object>(ProfileTypeField).ToString()));
// do other stuff, then check for dups...
var Dups = ClientProfiles.AsParallel()
.GroupBy(x => new { InterfaceID = x.Field<object>(InterfaceField).ToString(), ProfileType = x.Field<object>(ProfileTypeField).ToString() })
.Where(z => z.Count() > 1)
.Select(z => z);
C # 7.1 o superiore utilizzando Tuples
e Inferred tuple element names
:
// declarative query syntax
var result =
from x in table
group x by (x.Column1, x.Column2) into g
select (g.Key.Column1, g.Key.Column2, QuantitySum: g.Sum(x => x.Quantity));
// or method syntax
var result2 = table.GroupBy(x => (x.Column1, x.Column2))
.Select(g => (g.Key.Column1, g.Key.Column2, QuantitySum: g.Sum(x => x.Quantity)));
C # 3 o superiore con anonymous types
:
// declarative query syntax
var result3 =
from x in table
group x by new { x.Column1, x.Column2 } into g
select new { g.Key.Column1, g.Key.Column2, QuantitySum = g.Sum(x => x.Quantity) };
// or method syntax
var result4 = table.GroupBy(x => new { x.Column1, x.Column2 })
.Select(g =>
new { g.Key.Column1, g.Key.Column2 , QuantitySum= g.Sum(x => x.Quantity) });
var Results= query.GroupBy(f => new { /* add members here */ });
.GroupBy(x => (x.MaterialID, x.ProductID))
.GroupBy(x => x.Column1 + " " + x.Column2)
gruppo x da new {x.Col, x.Col}
Una cosa da notare è che è necessario inviare in un oggetto per le espressioni lambda e non è possibile utilizzare un'istanza per una classe.
Esempio:
public class Key
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
Questo compilerà ma genererà una chiave per ciclo .
var groupedCycles = cycles.GroupBy(x => new Key
{
Prop1 = x.Column1,
Prop2 = x.Column2
})
Se wan't per citarne le proprietà chiave e poi retreive li si può fare in questo modo, invece. Ciò GroupBy
correttamente e vi consegnerà le proprietà chiave.
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;
}