LINQ Count로 항목 수를 구하는 방법: C#
약 1분 읽기

집계 작업 Aggregators
집계 작업은 집합 모든 요소를 계산하여 하나의 값으로 반환하는 작업입니다. 집계 작업에 해당하는 LINQ 메서드로는 Count , Sum , Min , Max , Average , Aggregate 가 있습니다.
Count
집합 내 요소 개수 세기
int[] factorsOf300 = { 2, 2, 3, 5, 5 };
int uniqueFactors = factorsOf300.Distinct().Count();
// uniqueFactors = 3
Distinct 메서드로 중복되는 값인 2와 5를 하나씩 제거한 뒤, 개수를 셉니다.
집합 내 조건에 맞는 요소 개수 세기
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);
// oddNumbers = 5;
public static int Count (this System.Collections.Generic.IEnumerable source, Func predicate )
Count 메서드에 조건을 람다 함수로 제공하여 조건에 맞는 요소를 셀 수 있습니다.
쿼리 문 내에서 그룹 개수 세기
List customers = GetCustomerList();
var orderCounts = from c in customers
select (c.CustomerID, OrderCount: c.Orders.Count());
각 Customers 별로 Order가 몇개 있는지 셉니다.
List
products = GetProductList(); var categoryCounts = from p in products group p by p.Category into g select (Category: g.Key, ProductCount: g.Count()); ``` Category 별로 해당하는 Product가 몇 개 있는지 셉니다.