簡體   English   中英

Linq查詢以按分組和計數顯示結果網格

[英]Linq query to show grid of results with group by and count

我正在努力處理涉及Group By和Count的LINQ查詢,希望有人能提供幫助。

我的模型是:

Class Person 
{
    public string Name
    public string Company
    public string Role

}

我的數據是:

Person1    IBM         Technician
Person2    IBM         Analyst
Person3    Microsoft   Engineer
Person4    Microsoft   Analyst
Person5    Apple       Analyst

我想要的輸出是:

         Technician    Engineer   Analyst     Total
IBM           1           0          1          2
Microsoft     0           1          1          2
Apple         0           0          1          1
          =========================================
              1           1          3          5

有人可以幫忙嗎?

var result = from person in persons
            group person by new { person.Role, person.Company }
            into g 
            select new { Role = g.Key, Company = g.Key.Company, Count = g.Count(item => item.Company == g.Key.Company )};

var countRole = result.Count(item => item.Role.Role == "Analyst"); // output: 3
var total = result.Count(); // output: 5
var countCompany = result.Count(item => item.Company == "IBM"); // output: 2

您可以定義擴展方法

public static class Extensions
{
    public class Table<Column, Row>
    {
        public List<Column> Columns;
        public List<Row> Rows;
        public List<List<int>> Cells;
        public List<int> ColTotals;
        public List<int> RowTotals;
    }

    private static List<P> GetValues<T, P>(IEnumerable<T> source, Func<T, P> selector)
    {
        return source.Select(selector).OrderBy(x => x).Distinct().ToList();
    }

    public static Table<Column, Row> ToTable<T, Column, Row>(this IEnumerable<T> source, Func<T, Column> columnSelector, Func<T, Row> rowSelector)
    {
        var cols = GetValues(source, columnSelector);
        var rows = GetValues(source, rowSelector);
        var cells = rows.Select(r => cols.Select(c => source.Count(x => columnSelector(x).Equals(c) && rowSelector(x).Equals(r))).ToList()).ToList();

        return new Table<Column, Row>() 
            {
                Columns = cols,
                Rows = rows,
                Cells = cells,
                ColTotals = cols.Select((x, i) => cells.Sum(c => c[i])).ToList(),
                RowTotals = cells.Select(x => x.Sum()).ToList(),
            };
    }
}

並像下面一樣使用它

var table = GetPersons().ToTable (p => p.Role, p => p.Company);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM