C#将foreach循环的格式设置为Lambda - c#

我正在开始使用C#,并获得了以下课程:

using System;
using System.Collections.Generic;

class PrefixMapSum : Dictionary<String, int> {

    public bool insert(String key, int value) {
        return base.TryAdd(key, value);
    } 

    public int sum(String prefix) {
        int sum = 0;

        foreach (String key in base.Keys) {
            if (key.StartsWith(prefix)) {
                sum = sum + base[key];
            }
        }

        return sum;
    }
}

现在,我希望使用lambda-expressions缩短代码的以下部分:

        foreach (String key in base.Keys) {
            if (key.StartsWith(prefix)) {
                sum = sum + base[key];
            }
        }

我尝试了:

new List<String>(base.Keys).ForEach(key => key.StartsWith(prefix) ? sum = sum + base[key] : sum = sum);

但是我遇到了这个错误:CS0201

我来自Java,我不太清楚为什么它不起作用。谁能解释我应该做些什么(以及为什么)?

参考方案

只有在过滤后至少有一个元素时,这才起作用。

base.Keys
   .Where(key=> key.StartsWith(prefix))
   .Sum(base[key])

如果不存在(方法不能求和),则可以使用此方法

base.Keys
   .Where(key=> key.StartsWith(prefix))
   .Select(key=> base[key])
   .DefaultIfEmpty(0)
   .Sum()

出于性能原因,您可能希望避免使用索引器,而是自己迭代字典。

var defaultZero = new KeyValuePair<string, int>(string.Empty, 0);
var sum = this
          .Where(pair => pair.Key.StartsWith(prefix))
          .DefaultIfEmpty(defaultZero)
          .Sum(pair => pair.Value);

LeetCode题解1879. Two Sum VII

给定一个已经 按绝对值升序排列 的数组,找到两个数使他们加起来的和等于特定数。函数应该返回这两个数的下标,index1必须小于index2。注意返回的值是0-based。请使用双指针完成本题,否则你有可能会被取消比赛资格。注意事项:```- 数据保证nums中的所有数的互不相同的。- nums数组长度≤100000- nums内的数≤1000000000``…

Isset与array_key_exists - php

isset或array_key_exist在哪里适合使用?就我而言,两者都有效。if( isset( $array['index'] ) { //Do something } if( array_key_exists( 'index', $array ) { //Do something } 参考方案 参见:http:…

LeetCode题解371.sum-of-two-integers

题目地址 https://leetcode.com/problems/sum-of-two-integers/description/ 题目描述 Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example 1: …

Java中的OrderByDecending(LINQ)等效项 - java

嗨,我是一名使用Java的C#开发人员。问题很简单:我如何才能将下面的c#代码写入Java并仍能正常工作:myCoffeeList.OrderByDescending(x => x.Name?.ToLower()?.Trim() == sender.Text.ToLower()?.Trim())); 我的sender.Text基本上是一个文本框。文本的…

LINQ RemoveAll代替循环 - c#

我有两个for循环,用于从列表中删除项目。我正在为这些循环寻找等效的LINQ语句for (Int32 i = points.Count - 1; i >= 0; i--) { for (Int32 j = touchingRects.Count - 1; j >= 0; j--) { if (touchingRects[j].HitTest(po…