Linq查询以分组和计数显示结果网格

时间:2015-04-04 10:16:28

标签: c# linq

我正在努力处理涉及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

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以定义扩展方法

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);
相关问题