在LINQ中将字符串与整数进行比较

时间:2019-04-05 12:29:54

标签: c# linq

从CSV文件导入数据,我正在尝试回答一些问题。当我尝试使用LINQ回答问题时,

  

“什么年谋杀案少于15000年?”

在尝试将列表中的string值与int 15000进行比较时,我陷入了困境。

我尝试了解析并试图将转换转换为Int32,但无济于事。我还尝试过将IEnumerableList类型更改为 integers ,也都没有成功。

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 + "");
    }
}

我看到编译时错误

  

“无法将'<'操作数应用于String和int类型”

但是我希望LINQ能够看到yearmurder以上的每个15000

1 个答案:

答案 0 :(得分:1)

我们使用一些不同的设计:单个集合(列表)或 custom 类(在下面的示例中为 anonymous ):

 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(); 

现在我们有data,它很容易查询:

 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));
相关问题