2009-03-06 30 views
0

Aşağıdaki kodda neden aşağıdaki hatayı alıyorum?LINQ ile genel bir listeden özel bir nesne nasıl alınır?

Özel bir nesneyi, kendi türünün Genel Listesine koyarsam IEnumerable'ın halledileceğini düşündüm. Üzerinde LINQ kullanmak için bu listeye başka ne yapmalıyım?

dolaylı türünü dönüştürülemez 'System.Collections.Generic.IEnumerable <TestLinq23.Customer>' için '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; } 
    } 

} 

cevap

2

Sen Single() için bir çağrı eklemeniz gerekir - aksi takdirde döndürüyor Müşteriler için dizisi.

Aynı zamanda, burada bir sorgu ifadesi kullanmak için gerçek bir ihtiyaç yoktur.

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

bu bir hata durumudur mı: bir yüklemi almaya Single() bir aşırı yük var, çünkü

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

Aslında, bu daha basit yapabilirsiniz: O nokta işaretini kullanımı daha basit olacak tam olarak bir eşleşme yoksa? Değilse, Single() yerine First()'u kullanmak isteyebilirsiniz.

DÜZENLEME: hiçbir sonuçları olabilir eğer, Garry tarafından işaret ettiğine SingleOrDefault() veya FirstOrDefault() isteyebilirsiniz - Bunlardan ikisi null dönecektir eğer hiç girdi maç.

+0

Bir kaydın var olmaması için geçerliyse * OrDefault() değişkenlerine de ihtiyaç duyabilir. –

+0

Evet, bunu cevaba ekleyeceğim. –

+0

Ayrıca bir yüklemi alarak aşırı yükünü de unutmuştum - daha basit :) –

İlgili konular