唯一对象计数不是以String的形式计数,而是char [英] Unique object counts are not getting counted in form of String but char

查看:65
本文介绍了唯一对象计数不是以String的形式计数,而是char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似下面的列表

I have a List like below

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以及如何解决这个问题.

Not sure why Type is breaking into char and how to fix this.

推荐答案

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>.

The reason your code didn't work is, SelectMany takes an IEnumerable<IEnumerable<T>> and flattens it to IEnumerable<T>. Since string inplements IEnumerable<char>, SelectMany treats IEnumerable<string> as IEnumerable<IEnumerable<char>> and the result is IEnumerable<char>.

这篇关于唯一对象计数不是以String的形式计数,而是char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆