C# .Net WinForms 应用程序 : anonymous collection- how to caste return type

标签 c# .net winforms casting anonymous-types

这对我来说似乎是一个重复问题。当我使用匿名集合时,我再次遇到类型转换问题。我对 XML 文件的查询返回字符串值的集合。我试图将这些值从数据访问层返回到业务逻辑层。提前致谢。

    public string[] getCustDetails(string customerId)
    {
        //Pulls customer information for selected customer
        var doc = XDocument.Load("Portfolio.xml");
        var custRecord = from account in doc.Descendants("acct")
                         let acct = account.Element("acct")
                         where (string)account.Attribute("custid").Value == customerId
                         select new
                         {
                             Fname = (string)account.Attribute("fname").Value,
                             Lname = (string)account.Attribute("lname").Value,
                             Ssn = (string)account.Attribute("ssn").Value,
                             Dob = (string)account.Attribute("dob").Value,
                             Custid = (string)account.Attribute("custid").Value
                         };
return ?????

    }

最佳答案

不能将匿名类型用作方法的参数或返回类型。

我建议使用您需要的属性创建一个简单的类,并使用它而不是匿名类型。

public class AccountDetails
{
  public string FName { get; set; }
  public string LName { get; set; }
  public string Ssn { get; set; }
  public string Dob { get; set; }
  public string Custid { get; set; }
}

public IEnumerable<AccountDetails> getCustDetails(string customerId)
{
    //Pulls customer information for selected customer
    var doc = XDocument.Load("Portfolio.xml");
    var custRecords = from account in doc.Descendants("acct")
                     let acct = account.Element("acct")
                     where (string)account.Attribute("custid").Value == customerId
                     select new AccountDetails
                     {
                         Fname = (string)account.Attribute("fname").Value,
                         Lname = (string)account.Attribute("lname").Value,
                         Ssn = (string)account.Attribute("ssn").Value,
                         Dob = (string)account.Attribute("dob").Value,
                         Custid = (string)account.Attribute("custid").Value
                     };

    return custRecords;
}

关于C# .Net WinForms 应用程序 : anonymous collection- how to caste return type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8029429/

相关文章:

c# - 在 C# 中使用什么控件来获取自定义选中的列表框?

c# - 在构造函数中引用 "this"可以吗?

c# - 重命名和复制程序集是否安全?

c# - .NET - 降低应用程序权限

c# - 什么是 NHibernate,我为什么要使用它?

c# - 我真的需要在集合上使用 AsQueryable() 吗?

c# - 全屏 Windows 窗体超越了屏幕尺寸

c# - 带有StreamWriter的StreamReader显示性能较低的PowerShell,但File.ReadLines

c# - 应用程序不会在其他计算机上运行/打开

.net - 如何为两列的值范围实现查找表