c# - 在 LINQ 查询中找不到 WHERE
问题描述
我正在尝试编写一个程序,该程序从 .csv 文件中获取汽车详细信息,然后将每辆汽车的特定详细信息添加到列表对象中。
我无法使用 LINQ 查询来查找列表中具有特定 make 值的所有汽车CITROEN
。
它给了我错误:
找不到源类型“CarList”的查询模式的实现。'哪里' 没有找到。
我的也这么说foreach
:
foreach 语句不能对“?”类型的变量进行操作 因为 '?' 不包含“GetEnumerator”的公共实例定义
我究竟做错了什么。我关注了有关如何使用 LINQ 的 Microsoft 页面,但我不明白该错误。
这是我的程序类:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqPractical
{
class Program
{
static CarList carList = new CarList();
static void Main(string[] args)
{
Car car = new Car();
StreamReader reader = new StreamReader(File.OpenRead(@"F:\\motfailures.csv"));
string header = reader.ReadLine();
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
var values = line.Split(',');
car.Make = values[0];
car.Model = values[1];
car.Year = values[2];
car.Pass = values[3];
car.Fail = values[4];
carList.Add(car);
Console.WriteLine("Added car to list with details:");
Console.WriteLine("Make: " + values[0]);
Console.WriteLine("Model: " + values[1]);
Console.WriteLine("Year: " + values[2]);
Console.WriteLine("Pass: " + values[3]);
Console.WriteLine("Fail: " + values[4]);
}
Console.ReadKey();
ShowMake();
}
public static void ShowMake()
{
var query = from car in carList
where car.Make == "CITROEN"
select car;
foreach (Car c in query)
{
Console.WriteLine("Make: " + c.Make + " Model: " + c.Model + " Year: " + c.Year);
}
}
}
}
列表类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqPractical
{
class CarList
{
private List<Car> _list = new List<Car>();
public void Add(Car newCar)
{
_list.Add(newCar);
}
}
}
和汽车类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqPractical
{
public class Car
{
private string _make;
private string _model;
private string _year;
private string _pass;
private string _fail;
public string Make
{
get
{
return _make;
}
set
{
_make = value;
}
}
public string Model
{
get
{
return _model;
}
set
{
_model = value;
}
}
public string Year
{
get
{
return _year;
}
set
{
_year = value;
}
}
public string Pass
{
get
{
return _pass;
}
set
{
_pass = value;
}
}
public string Fail
{
get
{
return _fail;
}
set
{
_fail = value;
}
}
}
}
解决方案
您得到的错误是因为您的 CarList 类没有实现 IEnumerable。Igor 关于使用 List 的评论是正确的方法,除非您需要创建自己的列表类型所提供的特定功能。如果不需要,不要过度设计解决方案。
推荐阅读
- angular - Angular 8 - routerLink vs [routerLink] 结合 routerLinkActive 问题
- google-cloud-platform - 计算引擎 VM 实例 CENTOS7 中的 Bq 命令行错误
- javascript - 外部插件第一次没有加载
- python - 将字典的numpy ndarray转换为DataFrame
- php - 改变产品档案的布局 Woo Commerce
- java - java rabbitmq 与 Executor 线程,创建的线程保持运行。如何确保线程被杀死?
- r - 比较跨地区的调查结果
- upgrade - 在 WSL 分布之间迁移数据
- django - 无法在模型中保存 GeoDjango 点
- reactjs - react-spring 等效于 react-pose PoseGroup