Domanda

Perché viene visualizzato il seguente errore nel seguente codice?

Ho pensato che se avessi messo oggetti personalizzati in un elenco generico del suo tipo, allora IEnumerable sarebbe stato curato? Cos'altro devo fare a questo Elenco per utilizzare LINQ su di esso?

  

Impossibile convertire implicitamente il tipo   '<TestLinq23.Customer> System.Collections.Generic.IEnumerable'   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; }
    }

}
È stato utile?

Soluzione

Devi aggiungere una chiamata a <= > - altrimenti restituisce una sequenza di clienti.

Allo stesso tempo, non è necessario utilizzare un'espressione di query qui. Sarà più semplice usare la notazione punto:

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

In effetti, puoi renderlo ancora più semplice, perché c'è un sovraccarico di Single() prendere un predicato:

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

È una condizione di errore se non esiste esattamente una corrispondenza? In caso contrario, potresti voler utilizzare First() anziché SingleOrDefault().

EDIT: come sottolineato da Garry, se potrebbero esserci nessun potresti voler FirstOrDefault() o null - entrambi restituiranno <=> se nessuna voce corrisponde.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top