c# - 在静态类中返回多个值

标签 c# asp.net string linq return

如何在后续类中返回 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/

相关文章:

javascript - 标记模板文字混淆

java - 与数组中的字符串匹配的最长子字符串

c# - 始终在桌面上保留表格(无 Win+D 效果)

c# - 可以将其当前计数减少 N(N>=1)的信号量?

.net - asp.net LinkBut​​ton 超链接问题

java - 使用 string.reverse 最长字符串回文

c# - 提取 HTTP POST 数据 (WCF C#)

c# - 调整捕捉 View 大小时没有 SizeChanged 事件

ASP.net Web 资源与图像

mysql - 从sql数据库检索图像并将其放入datalist