【问题标题】:Return Type of a method while returning multiple column in asp.net?在asp.net中返回多列时返回方法的类型?
【发布时间】:2015-01-17 10:42:27
【问题描述】:

我正在使用实体框架(edmx 文件)在 asp.net c# 中处理 MVC。我在使用 LINQ 查询返回多个列时遇到问题。我的查询工作正常,唯一的问题是方法的返回类型。

public List<string> searchcollege(string prefix)
{
  try
  {
    List<string> clglist = new List<string>(from a in objYaphie.TblYP_CollegeProfile 
                                            where a.SchoolName.StartsWith(prefix) 
                                            select a.CollegeId,a.SchoolName);
    return clglist;
  }
  catch (Exception e)
  {
    Console.Write(e);
  }
  return null;  
}

【问题讨论】:

  • 有什么问题?
  • 我想知道的是,上面代码块中方法的返回类型应该是什么。由于我从两列中检索数据,我不能使用 list 作为它的返回类型。

标签: c# asp.net-mvc model-view-controller


【解决方案1】:

您可以使用Tuple

var clglist = new List<Tuple<int,string>>(from a in objYaphie.TblYP_CollegeProfile 
                               where a.SchoolName.StartsWith(prefix) 
                               select Tuple.Create(a.CollegeId,a.SchoolName));

或者,为了使其更具可读性,您可以创建自定义类型并返回该类型的列表。

【讨论】:

  • 您的解决方案导致错误“System.Tuple`2[System.Int32,System.String] 无法序列化,因为它没有无参数构造函数”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-12
  • 2012-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多