问题描述
假设我有这样的列表:
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等...我所知道的是前两个项目是字符串,其余是整数.
在这种情况下,所需的结果为 15 .
推荐答案
方法A 无条件跳过第2个,并假设其余的都是整数字符串:
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));
其他推荐答案
,没有假设前两个项目是字符串
int sum = _lstr.Select(s => {int i; return int.TryParse(s,out i) ? i : 0; }) .Sum();
其他推荐答案
非常容易:
list.Skip(2).Select(int.Parse).Sum();
问题描述
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");
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.
In this case the desired result is 15.
推荐答案
Method A Unconditionally skips the first 2 and assumes the rest are all integer strings:
var sum = _lstr.Skip(2).Select(int.Parse).Sum();
Method B Makes no assumtions:
var sum = _lstr.Aggregate(0, (x, z) => x + (int.TryParse(z, out x) ? x : 0));
其他推荐答案
without making the assumption that first two items are strings
int sum = _lstr.Select(s => {int i; return int.TryParse(s,out i) ? i : 0; }) .Sum();
其他推荐答案
Very easily:
list.Skip(2).Select(int.Parse).Sum();