2

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.

4

6 回答 6

5

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));
于 2013-04-30T19:48:34.543 回答
4

不假设前两项是字符串

int sum = _lstr.Select(s => {int i; return int.TryParse(s,out i) ? i : 0; })
               .Sum();
于 2013-04-30T19:49:58.237 回答
1

非常简单地:

list.Skip(2).Select(int.Parse).Sum();
于 2013-04-30T19:48:46.293 回答
1
var sum = _lstr.Skip(2).Sum(s => int.Parse(s));
于 2013-04-30T19:49:37.347 回答
1
 int num = 0; int sum  = 0;
 _lstr.ForEach(x => {Int32.TryParse(x, out num); sum +=num;});

只是为了证明如果 Int32.TryParse 失败,则输出变量将重置为零

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

 int num = 0; int sum  = 0;
 foreach(string s in _lstr)
 {
    bool result = Int32.TryParse(s, out num);
    Console.WriteLine("TryParse:" + result + " num=" + num);
 }

TryParse:False num=0
TryParse:False num=0
TryParse:True num=1
TryParse:True num=7
TryParse:True num=2
TryParse:True num=5
TryParse:False num=0
TryParse:True num=9
于 2013-04-30T19:50:56.947 回答
-5
int sum=0,i=0;       
foreach(string s in mylist){
    //in case of non integers
    try{
        i=int.parse(s);//you can put convert or tryparse too here
    } catch(Exception ex) {
        i=0;
    }
    sum=sum+i;
}

return sum;
于 2013-04-30T19:57:31.297 回答