2011-11-06 2 views
0

XML 파일을 반복하여 입금 목록을 캡처하고이를 비즈니스 로직 계층에 전달합니다. 반환 문에 익명 형식 컬렉션에 to.list에 대한 정의가 없다는 오류가 표시됩니다. 내가 반환 문 to.list을 남겨두면 나는 select에 캐스팅이 누락되었다는 오류를받습니다. 익명의 컬렉션을 목록으로 변환 할 수 없기 때문입니다. 이 문제를 어떻게 해결할 수 있습니까?WinForms의 컬렉션 캐스팅

데이터 액세스 레이어

public class DepositList 
{ 
    public string Depid { get; set; } 
    public string Amount { get; set; } 
    public string DepDate { get; set; } 
} 

public class DLDeposits 
{ 
    public List<DepositList> getDeposits(string customerid) 
    { 

     double sumDep = 0; 
     //Returns list of deposits for selected customer 
     var doc = XDocument.Load("Portfolio.xml"); 

     List<DepositList> result = from account in doc.Descendants("account") 
         from deposit in account.Elements("deposits") 
         where (string)account.Element("acct").Attribute("custid").Value == customerid 
         select new 
         { 
          Depid = (string)deposit.Attribute("depid").Value, 
          Amount = (string)deposit.Attribute("depamount").Value, 
          DepDate = (string)deposit.Attribute("depdate").Value 
         }.ToList(); 

     return result; 
    } 
} 

비즈니스 로직 계층

public double getDeposits(string customerId) 
    { 
     double sumDep = 0; 
     //Returns list of deposits for selected customer 
     var doc = XDocument.Load("Portfolio.xml"); 
     CustCount(doc); 

     DLDeposits obj = new DLDeposits(); 
     var depositList = obj.getDeposits(customerId); 

         for (int i = 0; i < NumCusts; i++) 
         { 
          BL_Deposit oDeposit = new BL_Deposit(); 
          oDeposit.DepAmt = Convert.ToDouble(depositList[i].Amount); 
          oDeposit.DepDate = Convert.ToDateTime(depositList[i].DepDate); 
          oDeposit.DepositId = Convert.ToInt32(depositList[i].Depid); 
          addDeposits(oDeposit); 
          sumDep += oDeposit.DepAmt; 
         } 
         return sumDep; 
     } 

답변

4

문제는 당신이 익명의 유형이 아닌 List<DepositList>의 새 목록을 만들 것입니다. 당신은 당신의 select 절을 변경해야합니다 : 나는 Value 재산의 사용을 제거했습니다

select new DepositList 
{ 
    Depid = (string) deposit.Attribute("depid"), 
    Amount = (string) deposit.Attribute("depamount"), 
    DepDate = (string) deposit.Attribute("depdate") 
} 

주 - 모두 문자열로 캐스트 그와 명시를 사용하여 필요하지 않았다 XAttribute에서 string으로 변환하면 속성이 누락 된 경우 NullReferenceException 대신 null이됩니다. DepositList 오히려 더 강하게 입력 된 경우

그러나,이 같은 더 나은 것이라고 저를 친다 :

그런 다음
public class DepositList 
{ 
    public int Depid { get; set; } 
    public decimal Amount { get; set; } 
    public DateTime DepDate { get; set; } 
} 

당신은 사용할 수 있습니다

select new DepositList 
{ 
    Depid = (int) deposit.Attribute("depid"), 
    Amount = (decimal) deposit.Attribute("depamount"), 
    DepDate = (DateTime) deposit.Attribute("depdate") 
} 

및 LINQ XML에 할 것입니다 당신을위한 전환. (모든 속성이없는 경우 내가 nullable이 아닌 값 형식을 사용하고 있는데이 경우는 , 예외가 발생합니다.) 나는 double 대신 Amountdecimal을했습니다

참고. 이 아닌은 재무 값으로 double을 사용해야합니다.