如何处理名单,LT的回报; AnonymousType&GT ;? [英] How to handle return of List<AnonymousType>?

查看:158
本文介绍了如何处理名单,LT的回报; AnonymousType&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
LINQ to SQL的:返回匿名类型

这是我的代码:

 class B
    {
        public int age { get; set; }
        public string name { get; set; }
    }

    class Program
    {
        static List<whatshouldIwritehere> GetList()
        {
            List<B> list = new List<B>() {
                new B(){ age = 10, name = "jaagu" },
                new B(){ age = 20, name = "juggu" },
                new B(){ age = 30, name = "jockey" },
                new B(){ age = 40, name = "jaggu" },
            };

            return (from item in list
                select new { MyAge = item.age, MyName = item.name }).ToList();
        }

        static void Main(string[] args)
        {

            Console.Read();
        }
    }



谁能告诉我我应该写在返回型函数的GetList()的?我知道查询创建一个匿名类,我想与整个函数类的工作。如果我创建MyAge和MYNAME定制类,那么它很容易给在返回类型。但是,有没有任何其他办法吗?有这一直是同样的功能,我会用var关键字。但我不能使用,在这里

Can anybody tell me what should I write in the return type of function GetList()? I know the query creates a anonymous class and I want to work with that class across functions. If I create a custom class with MyAge and MyName then it's very easy to give that in return type. However, is there any other way out ? Had this been in same function I would have used var keyword. But I can't use that here.

推荐答案

您可以返回列表<对象> 列表<动态方式>

如果您返回对象,那么你将无法除非有反射来访问属性。
如果返回的动态,那么你可以访问属性,但你失去了编译时检查。 (所以在属性名与一个错字会导致运行时异常)

If you return object then you won't be able to access the properties except with reflection. If you return dynamic then you can access the properties, but you lose the compile time check. (So a typo with in property name will result in a runtime exception).

编辑:
你需要指定类型显式地对了ToList功能:

You need to specify the type explicitely for the ToList function:

    static List<dynamic> GetList()
    {
        List<B> list = new List<B>() {
            new B(){ age = 10, name = "jaagu" },
            new B(){ age = 20, name = "juggu" },
            new B(){ age = 30, name = "jockey" },
            new B(){ age = 40, name = "jaggu" },
        };

        return (from item in list
                select new { MyAge = item.age, MyName = item.name }).ToList<dynamic>();
    }

这篇关于如何处理名单,LT的回报; AnonymousType&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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