如何从方法返回匿名类型? [英] How can I return an anonymous type from a method?

查看:31
本文介绍了如何从方法返回匿名类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个想要从多个地方调用的 Linq 查询:

I have a Linq query that I want to call from multiple places:

var myData = from a in db.MyTable
             where a.MyValue == "A"
             select new  {
                            a.Key,
                            a.MyValue
                          };

如何创建一个方法,将这段代码放入其中,然后调用它?

How can I create a method, put this code in it, and then call it?

public  ???  GetSomeData()
{
   // my Linq query
}

推荐答案

IQueryable 和 IEnumerable 都有效.但是您想使用特定于类型的版本,IQueryable<T> 或 IEnumerable <T>.

IQueryable and IEnumerable both work. But you want to use a type specific version, IQueryable<T> or IEnumerable <T>.

所以你需要创建一个类型来保存数据.

So you'll want to create a type to keep the data.

var myData = from a in db.MyTable
             where a.MyValue == "A"
             select new MyType
             {
                 Key = a.Key,
                 Value = a.MyValue
             };

这篇关于如何从方法返回匿名类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆