唯一对象计数不是以字符串的形式进行计数,而是以字符的形式进行计算

本文关键字:字符 计算 对象 唯一 字符串 | 更新日期: 2023-09-27 18:21:51

我有一个类似的列表

List<Product> products = new List<Product>();
Add(new Product { ProductId = "abc", Type = "Normal" });
Add(new Product { ProductId = "def",  Type = "Normal" });
Add(new Product { ProductId = "ghi",  Type = "VIP" });
Add(new Product { ProductId = "jkl",  Type = "Group" });
public Product Add(Product item)
{
    if (item == null)
    {
        throw new ArgumentNullException("item");
    }
    products.Add(item);
    return item;
}

我想像一样计数

Type: Normal Count: 2
Type: VIP Count: 1
Type: Group Count:1

我在下面写了代码

public string GetCount()
{
    int total = tickets.Count();
    string _text = "'nTotal " + total.ToString();
    var query = tickets.SelectMany(x => x.Type)
        .GroupBy(s => s)
        .Select(g => new { Name = g.Key, Count = g.Count() });
    foreach (var result in query)
    {
        _text += " Type: " + result.Name +  " Count: " + result.Count;
    }
    return _text;
}

我得到的输出是

Type: N Count: 2
Type: o Count: 3
Type: r Count: 3
Type: m Count: 2
Type: a Count: 2
Type: l Count: 2
Type: V Count: 1
Type: I Count: 1
Type: P Count: 1
Type: G Count: 1
Type: u Count: 1
Type: p Count: 1

不确定Type为什么会破坏char以及如何修复此问题。

唯一对象计数不是以字符串的形式进行计数,而是以字符的形式进行计算

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

代码不起作用的原因是,SelectMany取一个IEnumerable<IEnumerable<T>>并将其展平为IEnumerable<T>。由于string在元素IEnumerable<char>中,SelectManyIEnumerable<string>视为IEnumerable<IEnumerable<char>>,结果为IEnumerable<char>

using ConsoleApplication3;
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
    private static void Main(string[] args)
    {
        List<Product> products = new List<Product>();
        products.Add(new Product { ProductId = "abc", Type = "Normal" });
        products.Add(new Product { ProductId = "def", Type = "Normal" });
        products.Add(new Product { ProductId = "ghi", Type = "VIP" });
        products.Add(new Product { ProductId = "jkl", Type = "Group" });
        var result = from p in products
                     group p by p.Type into g
                     orderby g.Key
                     select new { Key = g.Key, Count = g.Count() };
        foreach (var r in result)
        {
            Console.Write(string.Format("Type: {0} Count: {1}", r.Key, r.Count));
        }
    }
}