Estoy usando C# en Framework 3.5. Estoy buscando agrupar rápidamente una Lista genérica <> por dos propiedades. Por el bien de este ejemplo, digamos que tengo una Lista de un tipo de orden con propiedades de IdCliente, IdProducto y CoberturaProducto. ¿Cómo obtendría la suma de ProductCounts agrupados por CustomerId y ProductId utilizando una expresión lambda?C# List <> GroupBy 2 Valora
Respuesta
var sums = Orders.GroupBy(x => new { x.CustomerID, x.ProductID })
.Select(group => group.Sum(x => x.ProductCount));
Alternativamente, si desea obtener los identificadores para cada suma, se podría hacer esto
var customerAndProductGroups =
from order in Orders
orderby order.CustomerID, order.ProductID // orderby not necessary, but neater
group order by new { order.CustomerID, order.ProductID };
foreach (var customerAndProductGroup in customerAndProductGroups)
{
Console.WriteLine("Customer {0} has ordered product {1} for a total count of {2}",
customerAndProductGroup.Key.CustomerID,
customerAndProductGroup.Key.ProductID,
customerAndProductGroup.Sum(item => item.ProductCount));
}
Soy consciente de que el hilo es muy antiguo, pero ya que acabo luchado a través de esta sintaxis pensé' d publicar mis hallazgos adicionales - se puede devolver la suma y las identificaciones (w/o foreach) en una consulta de este modo:
var sums = Orders
.GroupBy(x => new { x.CustomerID, x.ProductID })
.Select(group =>new {group.Key, ProductCount = group.Sum(x => x.ProductCount)});
la parte difícil para mí para conseguir que funcione es que la suma debe tener un alias, aparentemente ...
var New1 = EmpList.GroupBy (z => z.Age) .OrderBy (Employee => Employee.Key);
dataGridView1.DataSource = New1;
Esta respuesta no parece aplicarse a la pregunta. – Bryan
- 1. C# List <> Add() método rendimiento
- 2. ObservableCollection <> vs. List <>
- 3. C# Casting a List <ObjBase> como List <Obj>
- 4. List <> propia comparador
- 5. C# List <> Ordena por x then y
- 6. Casting List <> de la clase derivada a List <> de la clase base
- 7. List <> elementos con C# utilizando LINQ
- 8. Lista <? extiende Base> VS List <Base>
- 9. Queue <T> vs List <T>
- 10. C# Expandir lista plana <T> al diccionario <T, ICollection <int>>
- 11. C# List <> Ordenar por/Agrupar por/Eliminar
- 12. DataTable to List <object>
- 13. Sort List <DateTime> Descending
- 14. public List <(Of <(<'T>)>)> .. :: .. Enumerator?
- 15. Scala: groupBy (identity) of List Elements
- 16. C# List <T> Contiene la prueba
- 17. C# List <T> .ConvertAll en .NET 2.0
- 18. C# List <> Ordene con 3 propiedades .Net 2.0
- 19. SVG: Acerca del uso de <defs> y <use> con texto variable valora
- 20. C# Converting List <int> en la lista <double>
- 21. qué colección de C# usar en lugar de List <KeyValuePair <string, double >>?
- 22. C# Genéricos: Lista <Object> o nueva clase extends List <Object>
- 23. Diccionario <string, MyObject> o List <MyObject> con C# 3.5?
- 24. Cómo usar List <T> o Dictionary <T,T2> en C# WinRT componente
- 25. C# Convert List <string> a Dictionary <string, string>
- 26. List <T> to DataView
- 27. ¿Está std :: list <> :: sort stable?
- 28. Android save List <String>
- 29. return unknown Generic List <T>
- 30. cómo instanceof List <MyType>?
Me di cuenta de que esta respuesta es muy antigua, pero si alguien se preguntaba por qué es necesario el alias, las propiedades generan nombres de campo implícitos pero los métodos no. – Jimmy