2017-04-17 98 views
-1

我有以下Customer類:的GroupBy各個領域並獲得數

public class Customer 
{ 
    public string Name {get; set;} 
    public string Email {get; set;} 
    public string City {get; set;} 
} 

客戶收集

List<Customer> customers = //assigned range of customers 

現在我需要按所有領域。我不想選擇單個字段。在我的實際場景中,它運行得更加動態,所以我無法預先定義這些字段。

從這個customers對象,我需要構建一個矩陣像

Name | Email | City | count 
AB  [email protected]  ss  3 
CB  [email protected]  ss  2 
EF  [email protected]  ss  34 
ek  g.com  we  84 

我嘗試走這條路。通過多列

public static IEnumerable<GroupResult> GroupByMany<TElement>(
    this IEnumerable<TElement> elements, List<string> groupSelectors) 
{ 
    var selectors = 
     new List<Func<TElement, object>>(groupSelectors.Count); 
    foreach (var selector in groupSelectors) 
    { 
     LambdaExpression lambdaExpression = 
      System.Linq.Dynamic.DynamicExpression.ParseLambda(typeof(TElement), typeof(object), $"it[\"{selector}\"]"); 
     selectors.Add((Func<TElement, object>) lambdaExpression.Compile()); 
    } 
    return elements.GroupByMany(selectors.ToArray()); 
} 

,並調用它像

customers.GroupByMany(displayFields); 

問題 擴展方法組是我得到的結果作爲嵌套組

public class GroupResult 
{ 
    public object Key { get; set; } 
    public int Count { get; set; } 
    public IEnumerable Items { get; set; } 
    public IEnumerable<GroupResult> SubGroups { get; set; } 
    public override string ToString() 
    { 
     return $"{Key} ({Count})"; 
    } 
} 

這是從我要走了需要再次。

+0

你嘗試過什麼?請展示你的工作。 – Soviut

+0

什麼是「計數」?請顯示您迄今爲止所嘗試的內容。你是什​​麼意思矩陣?這是一個C#對象嗎? –

+0

我不確定你在問什麼或試圖在這裏做什麼。你只是想輸出它們嗎? –

回答

1

要組由整個對象和計數事件(或者換句話說「計數重複」)由迭代項只是組這樣的:

var result = from item in customers 
      group 1 by item into grouping 
      select new { 
       grouping.Key, 
       Count = grouping.Count() 
      }; 

對於採樣數據:

var customers = new List<Customer> 
{ 
    new Customer { Name = "a", City = "a" }, 
    new Customer { Name = "a", City = "a" }, 
    new Customer { Name = "a", City = "b" }, 
    new Customer { Name = "b", City = "b" } 
}; 

結果是:

enter image description here

請注意,由Customer對象分組使用其EqualsGetHashCode比較對象,然後確保覆蓋它們。你可以看一下this question

也看到對象的所有屬性都在Key性能不與你的榜樣輸出保持一致,但確實與所提供的GroupResult對準你顯示

+0

我認爲我過分複雜化了我的要求。謝謝@Gilad – HaBo

+0

@HaBo - 這是否適合你? –

+0

是的,它的工作。再次感謝 – HaBo