【问题标题】:linq creates new anonymous object; how to declare return type [duplicate]linq 创建新的匿名对象;如何声明返回类型[重复]
【发布时间】:2018-07-15 17:30:45
【问题描述】:

linq 表达式的细节并不重要,只是它创建了一个新的未命名对象:

 select new { ... }

因此我没有该函数的返回类型。必须有一个通用的无类型类型,比如 Javascript 的“any”。

   public ??? Get(int id)
    {
        var hisGrade = (from p in ctx.Students
                        where p.StudentID == id
                        select new { area = p.Grade.Section, name = p.Grade.GradeName }).FirstOrDefault();
        return hisGrade;
    }

我找到的每个示例都只显示了没有封闭函数的代码!

感谢您的帮助。 查克

【问题讨论】:

    标签: c# linq return-type anonymous


    【解决方案1】:

    您可以返回dynamic,它将在运行时声明一个具有两个属性的类型:areaname

       public dynamic Get(int id)
        {
            var hisGrade = (from p in ctx.Students
                            where p.StudentID == id
                            select new { area = p.Grade.Section, name = p.Grade.GradeName }).FirstOrDefault();
            return hisGrade;
        }
    

    因此您可以访问返回的对象的成员,但您会错过 IntelliSense 和编译时的类型检查:

    var name = Get(1).name;
    

    【讨论】:

      【解决方案2】:

      您是否假设它总是必须是由 Select 调用返回的匿名类型?你就错了。

      public struct MyType
      {
          public string Area { get; set; }
      
          public string Name { get; set; }
      }
      
      class Class1
      {
          public MyType Get(int id)
          {
              var hisGrade = (from p in ctx.Students
                              where p.StudentID == id
                              select new MyType{ Area = p.Grade.Section, Name = p.Grade.GradeName }).FirstOrDefault();
              return hisGrade;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多