求助:CS0103错误解析及C#代码逻辑讲解(customers未定义)
CS0103错误原因分析与代码讲解
错误详情
C:\Users\04albjoh\Downloads\VS code\app\Program.cs(20,30): error CS0103: The name 'customers' does not exist in the current context [C:\Users\04albjoh\Downloads\VS code\app\app.csproj]
原代码示例
// Example #1: var is optional when // the select clause specifies a string string[] words = { "apple", "strawberry", "grape", "peach", "banana" }; var wordQuery = from word in words where word[0] == 'g' select word; // Because each element in the sequence is a string, // not an anonymous type, var is optional here also. foreach (string s in wordQuery) { Console.WriteLine(s); } // Example #2: var is required because // the select clause specifies an anonymous type var custQuery = from cust in customers where cust.City == "Phoenix" select new { cust.Name, cust.Phone }; // var must be used because each item // in the sequence is an anonymous type foreach (var item in custQuery) { Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone); }
错误原因
CS0103错误的核心是:当前代码上下文里没有定义名为customers的变量/集合,编译器不知道customers是什么东西,自然无法执行LINQ查询。你尝试添加customers = {}没用,因为这只是赋值操作,但既没声明customers的类型,也没初始化出包含City、Name、Phone属性的有效集合——编译器依然不知道customers的结构,也找不到它的定义。
代码逐段讲解
Example #1 部分
这部分是正常的LINQ查询:
- 先定义了字符串数组
words,包含多个水果名称; - 用LINQ查询筛选出以字母
g开头的单词,这里var是可选的,因为查询返回的是IEnumerable<string>类型,你也可以写成IEnumerable<string> wordQuery = ...; - foreach循环里直接用
string类型接收每个元素,因为查询结果的元素都是字符串,完全匹配。
Example #2 问题部分
这部分的逻辑是想筛选出居住在Phoenix的客户,然后返回包含客户姓名和电话的匿名类型,但问题出在:
- 没有定义
customers集合,也没有定义对应的客户实体类,编译器识别不了cust.City、cust.Name这些属性; - 匿名类型的使用是没问题的,这里确实必须用
var来接收查询结果,因为匿名类型没有显式的名称,无法直接声明类型。
修正方案
要解决这个问题,你需要:
- 先定义一个
Customer类,包含Name、Phone、City属性; - 初始化一个
customers集合(比如List<Customer>或者数组),填充一些测试数据; - 再执行LINQ查询。
修正后的完整代码:
// 定义客户实体类 public class Customer { public string Name { get; set; } public string Phone { get; set; } public string City { get; set; } } // Example #1: var is optional when // the select clause specifies a string string[] words = { "apple", "strawberry", "grape", "peach", "banana" }; var wordQuery = from word in words where word[0] == 'g' select word; foreach (string s in wordQuery) { Console.WriteLine(s); } // Example #2: var is required because // the select clause specifies an anonymous type // 初始化customers集合 List<Customer> customers = new List<Customer> { new Customer { Name = "Alice", Phone = "123-4567", City = "Phoenix" }, new Customer { Name = "Bob", Phone = "987-6543", City = "New York" }, new Customer { Name = "Charlie", Phone = "456-7890", City = "Phoenix" } }; var custQuery = from cust in customers where cust.City == "Phoenix" select new { cust.Name, cust.Phone }; foreach (var item in custQuery) { Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone); }
内容的提问来源于stack exchange,提问作者albin3000
相关产品推荐
相关产品推荐

