【问题标题】:How to get a custom object out of a generic List with LINQ?如何使用 LINQ 从通用列表中获取自定义对象?
【发布时间】:2009-03-06 09:28:05
【问题描述】:

为什么在下面的代码中会出现以下错误?

我想如果我将自定义对象放在其类型的通用列表中,那么 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; }
    }

}

【问题讨论】:

    标签: linq ienumerable


    【解决方案1】:

    您需要添加对Single() 的调用 - 否则它会返回一个序列客户。

    同时,这里没有真正需要使用查询表达式。使用点表示法会更简单:

    Customer customerWithLinq = customerSet.Where(c => c.FirstName == "Joe")
                                           .Single();
    

    事实上,你可以让它更简单,因为有一个Single() 的重载来接受一个谓词:

    Customer customerWithLinq = customerSet.Single(c => c.FirstName == "Joe")
    

    如果没有完全匹配,这是否是一种错误情况?如果没有,您可能想使用First() 而不是Single()

    编辑:正如 Garry 所指出的,如果可能有 no 结果,您可能需要 SingleOrDefault()FirstOrDefault() - 如果没有匹配的条目,这两个都将返回 null。 p>

    【讨论】:

    • 如果记录不存在有效,可能还需要 *OrDefault() 变体。
    • 是的,我会将其添加到答案中。
    • 也忘记了使用谓词的重载 - 更简单:)
    • 不知道过载。让它更容易阅读。
    猜你喜欢
    • 1970-01-01
    • 2021-05-02
    • 2015-12-30
    • 2017-02-03
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    相关资源
    最近更新 更多