Home > Enterprise >  C# int32.TryParse after I read from a CSV file
C# int32.TryParse after I read from a CSV file

Time:10-13

My task is to import from a csv.

In the csv I have a 'Location Name' and Population' column (the location represents the number of population of a location), but some of the rows int the location column contains 'NA' instead of '0' and I have to work with those numbers.

I tried solving the problem in the following way:

First I read the population from the csv as a string, but after that I should convert it to int because I need to list the rows where the population is greater than a certain number.

Here is that example:

var task1 = from mergedStats in mergedDataCSV
                        orderby mergedStats.Population descending
                        where mergedStats.Population > 10000 // Here is the problem
                        select new
                        {
                            mergedStats.Name,
                            mergedStats.Population
                        };

Of course the '>' cant be applied to operands of type 'string' and 'int'. I tried int32.TryParse ( so the 'NA' value can be 0) but I cant use it in this current context.

Can you please help me with this problem?

CodePudding user response:

It would be better to read the data and parse it to in rather than do it in the query, but you didn't include your reading code so I can't directly advise how to modify it there. here's how you could do it in query:

where (int.TryParse(mergedStats.Population, out var pop) ? pop : 0) > 10000

TryParse returns a bool true if it worked, in which case the ? sees the true and returns the pop, which is an int variable created by TryParse's second argument - an out parameter containing the successfully parsed value. If parsing didn't succeed TryParse returns false, and the 0 is taken instead. If you want a different value in other future scenarios such as returning -1 if something didn't parse, you can alter it here

Note that you can perform the same technique in your reading code, and it would be better done there because it's done one time and can be queried over and over. It's a waste of resources to keep something as a string and convert it to int every time you need to use it

  • Related