如何在后续类中返回 FirstName 和 Surname?
public static string GetAccount(int AccountId)
{
LinqSqlDataContext contextLoad = new LinqSqlDataContext();
var q = (from p in contextLoad.MyAccounts
where p.AccountId == AccountId
select new { Name = p.FirstName, Surname = p.Surname }).Single();
return ??;
}
最佳答案
您可以返回强类型类、动态对象或元组。 我更喜欢返回强类型类。
使用 dynamic
类型的问题是你没有得到
仅在运行时智能感知和异常。
元组的问题是它没有告诉你什么 你回来。您或其他开发人员必须阅读该方法 知道名字和姓氏是什么。
示例
public class MyResult
{
public string Name { get; set; }
public string Surname { get; set; }
}
public static MyResult GetAccount(int AccountId)
{
LinqSqlDataContext contextLoad = new LinqSqlDataContext();
var q = (from p in contextLoad.MyAccounts
where p.AccountId == AccountId
select new MyResult{ Name = p.FirstName, Surname = p.Surname }).Single();
return q;
}
更新
我建议使用 SingleOrDefault
而不是 Single
。这将确保你
如果帐户不存在而不是抛出异常,则获取 null
结果。
//
select new MyResult{ Name = p.FirstName, Surname = p.Surname }).SingleOrDefault();
//
关于c# - 在静态类中返回多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11668515/