LINQ로 일반 목록에서 사용자 정의 객체를 얻는 방법은 무엇입니까?
-
03-07-2019 - |
문제
다음 코드에서 다음 오류가 발생하는 이유는 무엇입니까?
맞춤 개체를 일반적인 유형 목록에 넣으면 ienumerable이 처리 될 것이라고 생각 했습니까? 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; }
}
}
해결책
전화를 추가해야합니다 Single()
- 그렇지 않으면 a 순서 고객의.
동시에 여기에서 쿼리 표현식을 사용할 필요가 없습니다. 도트 표기법을 사용하는 것이 더 간단합니다.
Customer customerWithLinq = customerSet.Where(c => c.FirstName == "Joe")
.Single();
실제로 과부하가 있기 때문에 더 간단하게 만들 수 있습니다. Single()
술어를 취하기 위해 :
Customer customerWithLinq = customerSet.Single(c => c.FirstName == "Joe")
정확히 일치하지 않는 경우 오류 조건입니까? 그렇지 않다면 사용하고 싶을 수도 있습니다 First()
대신에 Single()
.
편집 : Garry가 지적한대로 아니요 당신이 원하는 결과 SingleOrDefault()
또는 FirstOrDefault()
-이 두 가지 모두 돌아올 것입니다 null
항목이 일치하지 않는 경우.
제휴하지 않습니다 StackOverflow