I have the following code that filters through a csv file and stores the 1st and 5th column in one list (values) and the 7th and 11th columns in another list (values1).
The aim is to search through each element in the first list (values) and then check every element in the second list (value1) for matching periods before adding all matching cases' payouts and then comparing to the first list's payout with a 1% error margin.
The following code takes care of the searching through each list part with the two foreach loops below. But I am having problems defining a variable (i.e. the var temp does not work and gives me an error of FormatException: Input string was not in a correct format." error when I run the code) to store or add the Payouts together in the event that there are multiple occurrences of a period in the second list.
Also is it possible to define the type of the variable Payout and Period when I define the lists? The problem lies with the fact that they are anonymous variables as supposed to defined ones.
Any help is appreciated, thanks.
var values = File.ReadLines(path).Skip(1)
.Select(x => x.Split(','))
.Where(x => x[0] != string.Empty)
.Select(x => new { Period = int.Parse(x[0]), Payout = decimal.Parse(x[4]) })
.ToList();
values = values.OrderBy(x => x.Period)
.ToList();
var values1 = File.ReadLines(path).Skip(1)
.Select(x => x.Split(','))
.Where(x => x[0] == string.Empty)
.Select(x => new { Period = int.Parse(x[6]), Payout = decimal.Parse(x[10]) })
.ToList();
//Console.WriteLine(values1);
values1 = values1.OrderBy(x => x.Period)
.ToList();
//Console.WriteLine(values1[0]);
decimal temp = 0;
foreach (var value in values)
{
foreach (var value1 in values1)
{
if (value.Period == value1.Period)
{
temp += value1.Payout;
}
}
}
FormatException means some of your data is not what you expect.
You can use something like the following to check for invalid data.
If you want to just ignore these lines you can invert the selection, eg
Note that
will fail if x[4] is an empty string, whereas you may want to interpret this as zero.