0

Importing data from a CSV file, I am trying to answer a few questions. When I try to use LINQ to answer the question,

"What years were there less than 15000 murders?"

I get stuck trying to compare string values located in my lists with the int 15000.

I have tried Parsing and trying to convert to Int32, but to no avail. I have also tried changing the IEnumerable and List types to integers and no success either.

using (StreamReader sr = new StreamReader(csvFile))
{
    List<string> years = new List<string>();
    List<string> murders = new List<string>();

    while (!sr.EndofStream)
    {
        var line = sr.ReadLine();
        var values = line.Split(',');

        years.Add(values[0]);
        murders.Add(values[1]);
    }

    IEnumerable<string> yearQuery = 
        from year in years
        where murders < 15000
        select year;

    foreach (string year in yearQuery)
    {
         Console.WriteLine(year + "");
    }
}

I see the compile time error,

"Can not apply '<' operand to type String and int"

but I expect the LINQ to see each year that murder is above 15000.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215

1 Answers1

1

Let's use a bit different design: single collection (list) or a custom classes (anonymous in the example below):

 var data = File
   .ReadLines(@"c:\csvFile.csv") // we don't have to work with Streams
   .Where(line => !string.IsNullOrWhiteSpace(line)) // to be on the safe side
   .Skip(1) // if we have a caption to skip
   .Select(line => line.Split(','))
   .Select(items => new {
      year = int.Parse(items[0]),
      murders = int.Parse(items[1]) 
    })
   .ToList(); 

Now we have data which is easy to query:

 var years = data
   .Where(item => item.murders < 15000)
   .Select(item => item.year)
   .OrderBy(year => year)    // let's sort the years
   .ToArray();

 Console.Write(string.Join(Environment.NewLine, years));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215