C# list <> GroupBy 2 값
-
21-08-2019 - |
문제
프레임 워크 3.5에서 C#을 사용하고 있습니다. 두 가지 속성으로 일반 목록 <>을 신속하게 그룹화하려고합니다. 이 예를 위해 CustomerID, ProductID 및 ProductCount의 속성이있는 주문 유형 목록이 있다고 가정 해 봅시다. Lambda Expression을 사용하여 CustomerID 및 ProductID로 그룹화 한 ProductCounts의 합을 어떻게 얻습니까?
해결책
var sums = Orders.GroupBy(x => new { x.CustomerID, x.ProductID })
.Select(group => group.Sum(x => x.ProductCount));
다른 팁
나는이 스레드가 매우 오래되었다는 것을 알고 있지만이 구문을 통해 어려움을 겪었 기 때문에 추가 결과를 게시 할 것이라고 생각했습니다.
var sums = Orders
.GroupBy(x => new { x.CustomerID, x.ProductID })
.Select(group =>new {group.Key, ProductCount = group.Sum(x => x.ProductCount)});
내가 작동하기에 까다로운 부분은 합계가 별명이어야한다는 것입니다.
또는 각 합에 대한 ID를 얻으려면이 작업을 수행 할 수 있습니다.
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));
}
var new1 = emplist.groupby (z => z.age) .OrderBy (Employee => Employee.key);
DatagridView1.Datasource = new1;
제휴하지 않습니다 StackOverflow