【问题标题】:Lambda to count occurences of a string in IEnumerableLambda 计算 IEnumerable 中字符串的出现次数
【发布时间】:2018-08-13 05:39:21
【问题描述】:

如何在单行 lambda 表达式中重写下面的 GetCounts() 方法?请注意,它必须是 lambda 表达式(不能是 LINQ)。我正在尝试做这样的事情,但无法弄清楚确切的语法:

return items.GroupBy(e => e).ToDictionary<string, int>(e => e,e => e.Count());

代码:

static void Main(string[] args)
{
    string[] colours = new string[] { "Blue", "Blue", "Green", "Red" };
    Dictionary<string, int> values = GetCounts(colours);

    foreach (KeyValuePair<string, int> v in values)
        Console.WriteLine($"{v.Key}:{v.Value}");

    //Desired output:
    //Blue:2
    //Green:1
    //Red:1
    Console.ReadKey();
}

public static Dictionary<string, int> GetCounts(IEnumerable<string> items)
{
    var counts = new Dictionary<string, int>();

    foreach (string item in items)
        counts[item] = !counts.ContainsKey(item) ? 1 : ++counts[item];

    return counts;
}

【问题讨论】:

  • items.GroupBy(e =&gt; e).ToDictionary&lt;string, int&gt;(e =&gt; e,e =&gt; e.Count()); 怎么不起作用?
  • items.GroupBy(e =&gt; e).ToDictionary(k =&gt; k.Key, v =&gt; v.Count());。你需要分组的Key

标签: c# asp.net .net lambda


【解决方案1】:

你需要分组的Key

items.GroupBy(e => e).ToDictionary(k => k.Key, v => v.Count());

【讨论】:

    猜你喜欢
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 2020-02-21
    • 2012-02-12
    相关资源
    最近更新 更多