Pregunta

¿Por qué aparece el siguiente error en el siguiente código?

Pensé que si ponía objetos personalizados en una lista genérica de su tipo, ¿me ocuparía IEnumerable? ¿Qué más necesito hacer con esta lista para usar LINQ en ella?

  

No se puede convertir implícitamente el tipo   'System.Collections.Generic.IEnumerable <TestLinq23.Customer>'   a '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; }
    }

}
¿Fue útil?

Solución

Debe agregar una llamada a <= > : de lo contrario, devolverá una secuencia de clientes.

Al mismo tiempo, no hay necesidad real de usar una expresión de consulta aquí. Será más sencillo usar la notación de puntos:

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

De hecho, puede hacerlo aún más simple, porque hay una sobrecarga de Single() tomar un predicado:

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

¿Es una condición de error si no hay exactamente una coincidencia? De lo contrario, es posible que desee utilizar First() en lugar de SingleOrDefault().

EDITAR: como señaló Garry, si puede haber no resultados, es posible que desee FirstOrDefault() o null : ambos devolverán <=> si no coinciden las entradas.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top