Search code examples
c#listsplitsumnumeric

Split on commas then sum numeric values one by one in C#


I have been trying to solve this problem for 3-4 hours and checked on internet many examples. I can split on commas; however, I cannot reach numeric values one by one and sum them.

var MyList = context.ProductAndPriceList();

I have string MyList and MyList's values like below,

"Apple,5"

"Computer,7"

"Mouse,12"

Result must be 5+7+12=24


Solution

  • Giving my answer as pseudo (c# based) code as I cannot tell which programming language you are using. The Below code is untested but should not be far off correct for C# .Net and outlines the logic behind getting the result you want. I expect you are forgetting to convert the value you are getting from the split method into an integer before trying to add them up. When you split a string even though the result you get looks like 5 it is actually still "5" (a string) if that makes sense.

    Edit: removed redundant code I noticed.

    //Your list
    var MyList = context.ProductAndPriceList(); 
    
    //My variables
    int total = 0;
    
    foreach(string val in MyList){
        //Split your string to get the number (still as a String)
        string str_number = val.split(',')[1];
        //Convert the number string into an int variable
        int int_number = int.Parse(str_number);
        //Add this value to the total
        total += int_number;
    }
    
    //Display the total count in the console to check its working.
    console.writeLine(total);