c# - How to get sum of the values from List?

后端 未结 4 1763
清酒与你
清酒与你 2021-01-03 20:22

I want to get sum of the values from list.

For example: I have 4 values in list 1 2 3 4 I want to sum these values and display it in Label

Code:



        
相关标签:
4条回答
  • 2021-01-03 20:34

    Use Sum()

     List<string> foo = new List<string>();
     foo.Add("1");
     foo.Add("2");
     foo.Add("3");
     foo.Add("4");
    
     Console.Write(foo.Sum(x => Convert.ToInt32(x)));
    

    Prints:

    10

    0 讨论(0)
  • 2021-01-03 20:47

    You can use LINQ for this

    var list = new List<int>();
    var sum = list.Sum();
    

    and for a List of strings like Roy Dictus said you have to convert

    list.Sum(str => Convert.ToInt32(str));
    
    0 讨论(0)
  • 2021-01-03 20:53

    How about this?

    List<string> monValues = Application["mondayValues"] as List<string>;
    int sum = monValues.ConvertAll(Convert.ToInt32).Sum();
    
    0 讨论(0)
  • 2021-01-03 20:57

    You can use the Sum function, but you'll have to convert the strings to integers, like so:

    int total = monValues.Sum(x => Convert.ToInt32(x));
    
    0 讨论(0)
提交回复
热议问题