Convert delimited record to seperate strings? - c#

On my web form I have a token box where the user can select multiple answers and it compiles them using a ~ to separate them. I am trying to add up a score on this page and I need to split those values. I tried using this and it says cannot explicitly convert char to string. Lets say the fields answer is 3~4~5
How would I convert that to 3 4 5 in a manner that would allow me to perform a calculation.
string List1 = threeriskfactors.Text.ToString();
string[] Vals1 = List1.Split('~');
String name1 = List1[0];
String name2 = List1[1];
I have had no problems adding up single values from a drop down list but this is stumping me. For my other calculations my code looks like this:
int a1 = Convert.ToInt32(cancerisabnormalcells.SelectedValue.ToString());
int b1 = Convert.ToInt32(cancerissecondcause.SelectedValue.ToString());
int d1 = Convert.ToInt32(americancancersociety.SelectedValue.ToString());
int final1 = a1 + b1 + d1;
How do I split the token boxes value so I can add it to this calculation?

If you want the Sum of them then it is as simple as:
int final = List1.Split('~').Select(s => int.Parse(s)).Sum();
To Validate each value to see if it is parseable before parsing, you can use ForEach method of List:
List1.Split('~').ToList().ForEach(s => { int a =0; int.TryParse(s, out a); final +=a; });

IEnumerable<int> vals1 = list1.Select(e=> Convert.ToInt32(e));
int final1=0;
foreach(int val in vals1)
{
final1 = final1 + val;
}
This should do it.

var total = 0;
foreach (var item in list1.Split('~'))
total += Int32.Parse(item);
By the way, I'm not sure how you're concatenating the values to get the tilde-delimited string. But, it's worth noting that HTML forms will automatically create semicolon-delimited list of values from HTML form elements that share the same name.

Related

Convert monetary string to array and total

I'm using c#, I have a string of cash entries I need to add together and get the total
arrTotalSplitCosts.Text = "24.90,10.60,1.90,20";
While the below works, as soon as I add a decimal point or a string value to replace the numbers in the array with my generated numbers, the below crashes
int[] arr = new int[] { 1, 2, 3 };
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
I want to take these values from a form post:
arrTotalSplitCosts.Text = "24.90,10.60,1.90,20";
And total them e.g. Total = 57.40
Anyone got any ideas, I'm struggling, thanks in advance.
The input is a string (not an array of string, but a single string).
You then have to take that string and split it into a list or array.
The values have decimals, so they cannot be dealt with as int. int is an integer; a whole number. You should deal with your data as a list of doubles.
When you convert from string to double, you should use tryparse, as you can more stringently enforce the conversion and check for exceptions as you go.
I've put a sample below, but note that I made it much more verbose than I normally would, just to (hopefully) more clearly show each of the steps.
If I was going to actually do this, I would use Linq more and combine multiple steps into single lines.
So something like this:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var inString = "24.90,10.60,1.90,20";
var stringValues = inString.Split(',');
List<double> doubleValues = new List<double>();
foreach(string v in stringValues){
double outNum;
double num = double.TryParse(v, out outNum)? outNum : 0;
doubleValues.Add(num);
}
Console.WriteLine(doubleValues.Sum(i => i)); // output = 57.4
}
}
Don't use , as a seperator. You can prefer ;.
For 10.000,00 formatting style
var sum = arrTotalSplitCosts.Text.Split(';').Select(decimal.Parse).Sum()
For 10,000.00 formatting style
var sum = arrTotalSplitCosts.Split(';').Select(a => decimal.Parse(a, CultureInfo.InvariantCulture)).Sum()

Package 3 chars of Array into an integer C#

So, i have this array which contains a bunch of numbers. I want to always take 3 of those chars and make one integer out of them. I haven't found anything on this yet.
here is an example:
string number = "123456xyz";
The string is what I have, these integers are what I want
int goal1 = 123;
int goal2 = 456;
int goaln = xyz;
It should go through all the chars and always split them into groups of three. I think foreach() is going to help me, but im not quite sure how to do it.
Something like this:
var goals = new List<int>();
for (int i = 0; i + 2 < number.Length; i += 3)
{
goals.Add(int.Parse(number.Substring(i,3)));
}
This has no error checking but it shows the general outline. Foreach isn't a great option because it would go through the characters one at a time when you want to look at them three at a time.
var numbers = (from Match m in Regex.Matches(number, #"\d{3}")
select m.Value).ToList();
var goal1 = Convert.ToInt32(numbers[0]);
var goal2 = Convert.ToInt32(numbers[1]);
...

Sum up numbers after splitting string and parsing to int

I am learning c# and I encounter problem when attempting to sum the numbers from console input. User inserts numbers separated with commas. Then, they get splitted and at the end they should be parsed to int's for the future calculations as sum.
Here is what I've got:
int[] convertedLine;
string stringLine = System.Console.ReadLine();
string[] splittedLine = stringLine.Split(' ');
var success = int.TryParse(splittedLine[0], out convertedLine);
System.Console.WriteLine(convertedLine[0] + convertedLine[1] + convertedLine[2]);
System.Console.ReadKey();
on 4th line I get error under convertedLine, that says 'cannot convert from out int[] to out int'.
I will appreciate help that will put me on the right track with my problem.
Thank you.
P
---------- edit ------------
Ok, so I've got this code now and it works. Is there a nicer way to do this parsing for all splitted elements of a string?
int[] convertedLine=new int[3];
string stringLine = System.Console.ReadLine();
string[] splittedLine = stringLine.Split(' ');
var success1 = int.TryParse(splittedLine[0], out convertedLine[0]);
var success2 = int.TryParse(splittedLine[1], out convertedLine[1]);
var success3 = int.TryParse(splittedLine[2], out convertedLine[2]);
System.Console.WriteLine(convertedLine[0] + convertedLine[1] + convertedLine[2]);
System.Console.ReadKey();
You need to initialize the elements of the convertedLine array and then specify the element you want to set to the value you pass to int.TryParse
Your .TryParse should look something like this:
var success = int.TryParse(splittedLine[0], out convertedLine[0]);
Note the [0] next to convertedLine that indicated the element in the int array you are setting
To initialize your convertedLine integer array simply do this line:
int[] convertedLine = new int[x];
Where x is the number of elements you want to have in your array. If you don't want to limit your user to a set amount of inputs you'll have to split on your split character and then initialize your integer array to however many values you found that the user input
The problem is here: int[] convertedLine; and then here: var success = int.TryParse(splittedLine[0], out convertedLine);
You are trying to parse to an array of integers a unique value of integers. Your code is assuming you have multiple integer as inputs
you are trying to convert the string to int in your case you pass an array of int and the function attempt to have an int a parameter.
try this one:
foreach(var i in splittedLine)
{
var success = int.TryParse(splittedLine[i], out convertedLine[i]);
}
The 'out' parameter from your int.TryParse is a single int. You're trying however to put that single int into an array of ints (which you've called 'convertedLine') without specifying where in the array that int should go.
One option then would be to declare your int array with a fixed size (eg)
int[5] convertedLine = new int[5];
which then allows for up to 5 integers. Then where you have
var success = int.TryParse(splittedLine[0], out convertedLine);
you should instead set a fixed value within the array, like this:
int.TryParse(splittedLine[0], out convertedLine[0]);
As an aside you also probably want to try and parse any other ints in the same way, eg:
int.TryParse(splittedLine[1], out convertedLine[1]);
int.TryParse(splittedLine[2], out convertedLine[2]);

how to get values from text using .IndexOf and .Substring in c#?

I need to make a summation for several values out from string variable,
Here is my variable:
string strBillHeader = "Invoice Details
INVOICE_DATE,INVOICE_DESCRIPTION,VALUE,FROM_DATE,TO_DATE
01/11/2014,New Corpbundle 7,7,01/11/2014,30/11/2014
01/11/2014,New Corpbundle 7,-7,01/11/2014,30/11/2014
01/11/2014,New Corpbundle 7,7,01/11/2014,30/11/2014
01/11/2014,Missed Call ALERT with Offer,2,01/11/2014,30/11/2014"
I need to get out the VALUES which are (7,-7,7,2) in this case? and to get 9 as a result.
I tried to do it this way:
for (int x = 4; x <= countCommas - 3; x += 4)
{
int firstCommaIndex = strBillHeader.IndexOf(',', strBillHeader.IndexOf(',') + x);
int secondCommaIndex = strBillHeader.IndexOf(',', strBillHeader.IndexOf(',') + (x + 1));
string y = strBillHeader.Substring(firstCommaIndex + 1, 1);
chargeAmount = Convert.ToInt32(y);
//chargeAmount = Int32.Parse(strBillHeader.Substring(firstCommaIndex, secondCommaIndex - firstCommaIndex));
TotalChargeAmount += ChargeAmount;
//string AstrBillHeader = strBillHeader.Split(',')[0];
}
but it did not work since I keep getting 'V' in the y variable.
Any help will be appreciated
If those commas and newlines are always there, this should work:
var lines = strBillHeader.Split(Environment.NewLine).Skip(2);
int total = lines.Split(',').Sum(line => Convert.ToInt32(line[2]));
So, you split the invoice into lines and discard the first 2 ("Invoice Details" and "INVOICE_DATE,INVOICE_DESCRIPTION,VALUE,FROM_DATE,TO_DATE"). Then you split each line on the commas, and take the third value - the first is a date, the second is the "New Corpbundle 7" part, the third is your value. You parse that value as an int, and sum the whole lot.
You may find you need to filter out the lines properly, rather than just assuming you can skip the first two and use the rest, but this should get you started.

Get csv values to add up

I have created a new integer called int VactualSum = 0;
I need VactualSum to equal the sum of all the values in an object called singleSummary[i].actual. then display the results in a text box called actualsumsent.
singleSummary[i].actual has 4 numeric values that I want my result to be the total of them when added up. e.g 10,20,30,40 the actualsumsent text box should show the value 100.
{ int VactualSum = 0;
I thought maybe having -
Vactual = Vactual + function[i].actual;
Then to put it in the text box have -
actualsumsent.Text = System.Convert.ToString(returned.Vactual)
But this does not work, the section in the array I am trying to add up is -
function[i].account = el.Descendants("var").Where(x => (string)x.Attribute("name") == "account").SingleOrDefault().Attribute("value").Value;
Any advice would be appreciated.
Assuming singleSummary is an array (or IList<T>) then you can do:
actualsumsent.Text = singleSummary.Sum(s => s.actual).ToString();
EDIT: Looking at the edit to the question, it seems you want to sum a comma-separated string containing int values. In that case you can calculate the sum like this:
int sum = singleSummary[i].account.Split(",").Select(s => int.Parse(s)).Sum();
Note this will throw an exception if the string is not well-formed.
Am I missing something? Do you simply want to sum your values and place them into your text box? If you're using 3.5 or newer, you can use the following:
actualsumset.Text = singleSummary.Sum(q=>q.actual).ToString();
Otherwise, you could sum your array up the classic way:
int VactualSum = 0;
foreach(YourObject obj in singleSummary)
{
VactualSum+=obj.actual;
}
actualsumset.Text = VactualSum;
Is a Vactual a bit like a vacuole? Or is it like an actualValue?
Sum of Comma separate values as a input
public int getSum(String inputNumbersCSV)
{
String[] inputNumbers = inputNumbersCSV.Split(',');
int sumOfNum = 0;
for (int i = 0; i < inputNumbers.Length; i++)
{
sumOfNum = sumOfNum + int.Parse(inputNumbers[i]);
}
return sumOfNum;
}

Categories

Resources