在WinForms中强制转换集合

本文关键字:转换 集合 WinForms | 更新日期: 2023-09-27 18:13:53

我正在遍历XML文件以捕获存款列表,并将它们作为列表传递给业务逻辑层。我在我的返回语句上得到一个错误,说匿名类型集合不包含to.list的定义。如果我离开返回语句的to.list,我得到一个错误的select说,我错过了一个转换,因为它不能将匿名集合转换为列表。我该如何解决这个问题?

数据访问层

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;
        }

在WinForms中强制转换集合

问题是您正在创建一个匿名类型的新列表,而不是List<DepositList>。您只需要将select子句更改为:

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

请注意,我已经删除了Value属性的使用-您不需要将强制转换为字符串,并且通过使用从XAttributestring的显式转换,如果缺少该属性,您将最终使用null而不是NullReferenceException

然而,我突然想到如果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 to XML将为您完成转换。(在这种情况下,如果缺少任何属性,它抛出异常,因为我使用的是非空值类型。)

注意,我把Amount变成了decimal,而不是double。你应该使用double作为财务值。