2014-10-06 56 views
0

我有一個像下面唯一的對象計數顯示系統文本

List<Product> products = new List<Product>(); 

Add(new Product { ProductId = "abc", Type = "Normal", Status = "1" }); 
Add(new Product { ProductId = "def", Type = "Normal", Status = "2" }); 
Add(new Product { ProductId = "ghi", Type = "VIP" , Status = "1" }); 
Add(new Product { ProductId = "jkl", Type = "Group", Status = "1" }); 

public Product Add(Product item) 
{ 
    if (item == null) 
    { 
     throw new ArgumentNullException("item"); 
    } 
    products.Add(item); 
    return item; 
} 

我想指望像一個列表:

類型:正常計數:2 類型:VIP計數:1種 類型:集團次數:1

從早期的幫助

低於位置 Unique object counts are not getting counted in form of String but char

我寫代碼

var groups = products.GroupBy(x => new { x.Type, x.Status }).Select(g => string.Format("Type: {0} Count: {1}", g.Key, g.Count())); 

當運行上述我得到在組文本如下

System.Linq.Enumerable + WhereSelectEnumerableIterator 2[System.Linq.IGrouping 2 [<> f__AnonymousType0`2 [System.String,System.Int32]的LocalServer .Product],System.String] ##

不知道如何解決,或者我做錯了什麼。

回答

1

這應該可以解決您的問題。

List<Product> products = new List<Product>(); 
products.Add(new Product { ProductId = "abc", Type = "Normal", Status = "1" }); 
products.Add(new Product { ProductId = "def", Type = "Normal", Status = "2" }); 
products.Add(new Product { ProductId = "ghi", Type = "VIP" , Status = "3" }); 
products.Add(new Product { ProductId = "jkl", Type = "Group", Status = "1" }); 

IEnumerable<string> groupedProducts = products.GroupBy(product => product.Type) 
               .Select(grouping => string.Format("Type: {0} Count: {1}", grouping.Key, grouping.Count())); 

foreach (var groupedProduct in groupedProducts) 
{ 
    Console.WriteLine(groupedProduct); 
} 

的問題是,你被一些屬性的嘗試組,因爲你只需要通過Type來算,使用.GroupBy(product => product.Type),然後用.Select()投射在你想要的任何方式的結果。

+0

謝謝,這工作。 – MvsW 2014-10-06 04:39:33

+0

還有一個轉折點。我需要得到的計數,這有效,另外我還需要計數狀態像上面的示例計數狀態2,應顯示爲1/2。 Total Normal爲2,但其中一個狀態爲1. – MvsW 2014-10-06 06:56:39

+0

您能寫一個輸出結果的例子嗎? – 2014-10-06 07:01:32

1

您需要使用組Key屬性的Type屬性來獲取類型名稱,因爲您正在使用新的匿名類型進行分組。

var groups = products.GroupBy(x => new { x.Type, x.Status }).Select(g => string.Format("Type: {0} Count: {1}", g.Key.Type, g.Count()));