题
为什么我在以下代码中收到以下错误?
我想如果我将自定义对象放在其类型的通用List中,那么IEnumerable会被处理掉吗?我还需要对此List做什么才能使用LINQ?
无法隐式转换类型 'System.Collections.Generic.IEnumerable
<TestLinq23.Customer>
' 'TestLinq23.Customer'
using System;
using System.Collections.Generic;
using System.Linq;
namespace TestLinq23
{
class Program
{
static void Main(string[] args)
{
List<Customer> customerSet = new List<Customer>();
customerSet.Add(new Customer { ID = 1, FirstName = "Jim", LastName = "Smith" });
customerSet.Add(new Customer { ID = 2, FirstName = "Joe", LastName = "Douglas" });
customerSet.Add(new Customer { ID = 3, FirstName = "Jane", LastName = "Anders" });
Customer customerWithIndex = customerSet[1];
Console.WriteLine("Customer last name gotten with index: {0}", customerWithIndex.LastName);
Customer customerWithLinq = from c in customerSet
where c.FirstName == "Joe"
select c;
Console.WriteLine(customerWithLinq.LastName);
Console.ReadLine();
}
}
public class Customer
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
解决方案
您需要添加对 <=的调用> - 否则它将返回客户的序列。
同时,这里不需要使用查询表达式。使用点符号会更简单:
Customer customerWithLinq = customerSet.Where(c => c.FirstName == "Joe")
.Single();
事实上,你可以使它变得更简单,因为Single()
超载了一个谓词:
Customer customerWithLinq = customerSet.Single(c => c.FirstName == "Joe")
如果没有一个匹配,这是一个错误条件吗?如果没有,您可能想使用 First()
而不是SingleOrDefault()
。
编辑:正如Garry所指出的,如果可能有 no 结果,您可能需要 FirstOrDefault()
或 null
- 如果没有条目匹配,这两个都会返回<=>。
不隶属于 StackOverflow