似乎这对我来说是一个恢复问题。当我使用匿名集合时,我再次遇到类型转换的问题。我对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;
}
为需求创建新类,并将其作为列表返回…
public MyClass[] 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 MyClass
{
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
}).ToArray();
return custRecord;
}
将类定义为
public class MyClass
{
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; }
}
我将创建一个包含以下属性的新类。
string Fname
string Lname
string Ssn
string Dob
string Custid
然后从getCustDetails()方法返回此类型