2013-08-26 3 views
0

내가 만든 목록에서 특정 x 항목을 가져 오려고합니다.linq을 사용하여 목록에서 특정 x 항목 가져 오기

List<Item> il = (List<Item>)(from i in AllItems 
          where i.Iid == item.Iid 
          select i).Take(Int32.Parse(item.amount)); 

나는 다음과 같은 오류가 발생합니다 :

"Unable to cast object of type 'd__3a`1[AssetManagement.Entities.Item]' to type 'System.Collections.Generic.List`1[AssetManagement.Entities.Item]'."

가 고정 왜 이런 일이 될 수있는 방법

?

답변

5

KingKing이 올바르게 지적한대로 끝에 ".ToList()"통화가 누락되었습니다. 이 쿼리가 없으면 List에 캐스팅 할 수없는 IQueryable이 쿼리에 사용됩니다. '측면 노드로

, 나는 그것도 "ToList"하지 않고 예외를 발생하지 않았을,

var il = (from i in AllItems 
    where i.Iid == item.Iid 
    select i).Take(Int32.Parse(item.amount)).ToList(); 

처럼, 암시 적 변수 유형 선언을 사용하여이 방법을 선호하는 것 (하지만 어쩌면 그것은 같으면 예상했던대로되지 않았습니다.)

3
List<Item> il = (from i in AllItems 
       where i.Iid == item.Iid 
       select i).Take(Int32.Parse(item.amount)).ToList(); 

참고 : 주조 만 Inheritance 또는 Implementation 관계와 객체 사이에 수행 할 수 있습니다. 기억해보십시오.

3

이 구문을 읽기 쉽지 않습니까? 은`Take`는 [`TakeWhile`]와

List<Item> il = AllItems.Where(i => i.Iid == item.Iid) 
         .Take(Int32.Parse(item.amount)) 
         .ToList(); 

내가 쿼리 (from..where..select).ToList();

+0

병합 할 수 있습니다에게'Where'을 실현하기 위해 괄호를 사용하여 좋아 한 적이 (쿼리에서 유일한 차이는 ToList()입니다) 및 (http://msdn.microsoft.com/en-us/library/system.linq.enumerable.takewhile.aspx) – Default

+0

@Default 잘 모르겠습니다. 항목은 열거 시작 부분에 없을 수 있습니다. – EZI

+0

ups. 문서를 잘못 읽었습니다. 당신이 올바른지 – Default

관련 문제