2015-04-04 183 views
1

我正在努力與涉及分組依據和計數,並希望有人可以提供幫助的LINQ查詢。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 

是否有人可以幫忙嗎?

回答

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 
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);