唯一对象计数不会以String的形式计算,而是以char计

时间:2014-09-14 05:44:28

标签: c# linq list

我有一个如下所示的列表

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

2 个答案:

答案 0 :(得分:3)

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>

答案 1 :(得分:0)

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));
        }

    }
}