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;
}
Related
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()
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.
So I'm working in Visual Studio 2015 with a few custom classes. One of which is called MinPriorityQueue, and it is a priority queue that, in this situation, allows me to retrieve the object of MinimumPriority in the queue via a property MinimumPriority. There is also a method called RemoveMinimumPriority, which is self-explanatory.
I am not allowed to modify this method, it was pre-made for us for this assignment, otherwise I would have already found a simple solution.
My program is meant to compare two text files, and return a value based off a certain equation which isn't important as far as this post goes. The problem I am having is within my UserInterface code. Here is my click event for the 'Analyze' button on my GUI.
private void uxAnalyze_Click(object sender, EventArgs e)
{
Dictionary<string, StoreWord> dictionary = new Dictionary<string, StoreWord>();
const int _numFiles = 2;
MinPriorityQueue<float, StoreInfo> minQueue = new MinPriorityQueue<float, StoreInfo>();
int numWords1 = 0;
int numWords2 = 0;
//Process Both Input Files
using (StreamReader sr = new StreamReader(uxTextBox1.Text))
{
for (int i = 0; i < _numFiles; i++)
{
if (i == 0)
{
dictionary = ReadFile(dictionary, uxTextBox1.Text, i, out numWords1);
}
if (i == 1)
{
dictionary = ReadFile(dictionary, uxTextBox2.Text, i, out numWords2);
}
}
}
int[] numWords = new int[2];
numWords[0] = numWords1;
numWords[1] = numWords2;
//Get 50 Words with Highest Combined Frequencies
foreach(var entry in dictionary.Values)
{
StoreInfo freq = new StoreInfo(entry, numWords);
minQueue.Add(freq, Convert.ToSingle(entry[0] + entry[1]));
if(minQueue.Count > 50)
{
minQueue.RemoveMinimumPriority();
}
}
//Compute and Display the Difference Measure
float diffMeasure = 0;
float temp = 0;
foreach( x in minQueue)
for (int i = 0; i < minQueue.Count; i++)
{
temp += minQueue.????; //This is where my problem stems
}
diffMeasure = (float)(100 * Math.Sqrt(temp));
}
A few lines from the end you will see a comment showing where my problem is located. The MinPriorityQueue (minQueue) has two parameters, a Priority, and a Value, where the Priority is a Float, and the Value is another class called StoreInfo. This class has an Indexer, which will return information from a different file depending on what the index is. In this case, there are only two files. For example: StoreInfo[i] returns the frequency of a word in the ith text file.
Ideally, my code would look like this:
for (int i = 0; i < minQueue.Count; i++)
{
temp += (minQueue.minimumValue[0] - minQueue.minimumValue[1])*(minQueue.minimumValue[0] - minQueue.minimumValue[1]);
}
diffMeasure = (float)(100 * Math.Sqrt(temp));
Problem is, that would require a minimumValue property, which I don't have access to. All I have is minimumPriority.
As far as I can see, there is no other way for me to get the Values that I need in order to get the frequencies that I need to get from the indexer and put into the equation.
Help is much appreciated.
Alright guys, I've been thinking at this for far too long, and it doesn't seem like anyone else sees another solution either.
At this point, I'm just going to go with the logical solution and add another property into the MinPriorityQueue class, even though it is against my professor's wishes.
Thank you all anyway.
I have a listbox which contain some string ... and I would like to pass those string to an empty dropdownlist? Is it possible? Just the value in the listbox will be chosen.
I dont know what I'm doing .. And for this I have to use a for loop which I'm still confused about.
This is my code for now:
string [] lines = new string [cartListBox.Items.Count];
int select;
for (int i = 0; i < lines.Length ; i++)
{
select = cartListBox.SelectedValue
watchedMoviesDropDownList.Items.Add(cartListBox.Items.Count.ToString());
}
However, when I debug it, it gives me an error saying that index is out of range... :( Please help....!
It's much simpler to do it, you don't need:
string [] lines
nor:
int select
Just use this code:
for (int x = 0; x < cartListBox.Items.Count; x++)
watchedMoviesDropDownList.Items.Add(cartListBox.Items[x]);
Using array.ElementAt(0); we can get the element at index 0 of the array. Is there a method to get all the elements in an array?
string[] arr1 = {'abc', 'def', 'ghi'}
Library.Results["TEST_ACTUALVALUE"] = "The results are: " + arr1;
TEST_ACTUALVALUE is a column in my report.xls file. The above writes System.string[] in my excel file.
You already have all of the elements in the array...the array itself.
The simple answer is iterate over them:
foreach(var item in array)
{
// work with item here
}
Or if you'd rather deal with indexes:
for(var i = 0; i < array.Length; i++)
{
var item = array[i];
// work with item here
}
It's hard to know what you mean by "get all the elements in an array" because you already have all the elements....in the array.
If you mean concatinating a string from a string array then something like:
var concatinatedString = String.Concat(myArrayOfStrings);
There's a hundred ways to skin that cat. Largely it should depend on what you wish to do with all the elements. Heres the old school for loop method:
for(int i = 0; i < array.Length; i++)
{
something = array[i];
}
I'm not sure why you'd do this, but there is a array.All available. Try that?
Depending on what you want to get the elements for there are many methods you can look into
Get all the elements in an array
for(int x = 0; x < array.Length; x++)
{
something = array[x];
somethingElse = array.ElementAt(x);
}
Make an array a list to get all values:
List<T> myList = array.ToList<T>();
From here you can do all list methods with that array to get all values.
If you are trying to take the sum of every element use:
sum = array.Sum();
To get the max/min value in the array:
max = array.Max();
min = array.Min();
To get the average:
double average = array.Average(num => Convert.ToInt64(num));
There are many other ways to get all information from an array, here
The question is how to join a string array together. Solution:
... = "The results are: " + String.Join (", ", arr1);
And a note: you don't have to and should not use array.ElementAt(0) to get an element. Use array[0].
Going to go out on a limb here and recommend using a loop?
Why are you using ElementAt? You can just use the indexer:
var value = array[0];
In general:
var ithValue = array[i];
The Array class implements the IList, ICollection, and IEnumerable interfaces. So you can use any needed method of these interfaces.
Eventually, you can write foreach loop to traverse through array.
//IF the array type is string, you can follow below:
//else you need to convert to string 1st.
String Result = "";
For (int i=0; i<array.length; i++)
{
Result = Result + array[i];
}
// The result will consist all the array element.