Reputation: 159
I'm new to this site, and pretty new to programming, at the moment I'm trying to display a count amount for the users names on my donation list, and then I also want to have a sum to work out the total amount of money the donation list contains, If someone could help me with creating a way to add up amount of donors on the donations.txt file that would be great help, I have no idea where to start, but so far this is my coding:
string sName;
double dAmount;
string sTotalNames;
double dAmountTotal;
double dAmountAverage;
using (StreamReader sr = new StreamReader("Donations.txt"))
{
while (sr.Peek() != -1)
{
sName = sr.ReadLine();
Console.WriteLine(sName);
dAmount = Convert.ToDouble(sr.ReadLine());
Console.WriteLine(dAmount);
}
Console.WriteLine("Press any key to close");
Console.ReadKey();
}
Upvotes: 2
Views: 120
Reputation: 16553
A quick & compact implementation:
var lines = File.ReadAllLines("Donations.txt");
// Convert odd rows to Double
var amounts = lines.Where((x,i) => i % 2 == 1)
.Select(Convert.ToDouble)
.ToArray();
var sum = amounts.Sum();
var count = amounts.Count();
Upvotes: 1
Reputation: 3837
List<double> dAmountList = new List<double>();
using (StreamReader sr = new StreamReader("Donations.txt"))
{
while (sr.Peek() != -1)
{
sName = sr.ReadLine();
Console.WriteLine(sName);
dAmount = Convert.ToDouble(sr.ReadLine());
Console.WriteLine(dAmount);
dAmountList.Add(dAmount);
}
double sum = dAmountList.Sum(); //here you have your sum
int dAmountOfDonators = dAmountList.Count(); //here you have your donators total count
Console.WriteLine("Press any key to close");
Console.ReadKey();
}
Upvotes: 1
Reputation: 26068
Assuming everything else you have works correctly, creating a sum would be pretty easy.
string sName;
double dAmount;
int sTotalNames = 0;
double dAmountTotal = 0;
double dAmountAverage;
using (StreamReader sr = new StreamReader("Donations.txt"))
{
while (sr.Peek() != -1)
{
sName = sr.ReadLine();
Console.WriteLine(sName);
dAmount = Convert.ToDouble(sr.ReadLine());
Console.WriteLine(dAmount);
dAmountTotal += dAmount;
sTotalNames++;
}
dAmountAverage = dAmountTotal / sTotalNames;
Console.WriteLine("Sum = {0}", dAmountTotal );
Console.WriteLine("Total Names = {0}", sTotalNames);
Console.WriteLine("Average Amount = {0}", dAmountAverage);
Console.WriteLine("Press any key to close");
Console.ReadKey();
}
Upvotes: 3