我有一个如下所示的列表
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 [&LT;&GT; f__AnonymousType0`2 [System.String,System.Int32],LocalServer.Product],System.String] ##
不确定如何解决,或者我做错了什么。
答案 0 :(得分:1)
您需要使用组键属性的“类型”属性来获取类型名称,因为您要按新的匿名类型进行分组。
var groups = products.GroupBy(x => new { x.Type, x.Status }).Select(g => string.Format("Type: {0} Count: {1}", g.Key.Type, g.Count()));
答案 1 :(得分: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()
投影结果以任何你想要的方式。