对列表中的整数范围求和 [英] Sum a range of ints in a List

查看:66
本文介绍了对列表中的整数范围求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的列表:

Let's say I have a List like this:

List<string> _lstr = new List<string>();

        _lstr.Add("AA");
        _lstr.Add("BB");
        _lstr.Add("1");
        _lstr.Add("7");
        _lstr.Add("2");
        _lstr.Add("5");

如果我不知道列表中有多少个整数,如何求和列表中的整数?可能是4,可能是10,依此类推...我所知道的是,前两项是字符串,其余项是整数.

How do I sum up the integers in the List if I don't know how many integers are in the List? Could be 4, could be 10, etc... All I know is that the first two items are strings, the rest are integers.

在这种情况下,期望的结果是 15 .

In this case the desired result is 15.

推荐答案

方法A 无条件地跳过前2个,并假定其余都是整数字符串:

Method A Unconditionally skips the first 2 and assumes the rest are all integer strings:

var sum = _lstr.Skip(2).Select(int.Parse).Sum();

方法B 不做任何假设:

var sum = _lstr.Aggregate(0, (x, z) => x + (int.TryParse(z, out x) ? x : 0));

这篇关于对列表中的整数范围求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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