这对我来说似乎是一个重复问题。当我使用匿名集合时,我再次遇到类型转换问题。我对 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/