如何返回Generic.List< Anonymoustype>从C#中的函数 [英] How to return Generic.List<Anonymoustype> from a function in C#

查看:278
本文介绍了如何返回Generic.List< Anonymoustype>从C#中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP.NET 3.5 C#
我正在使用Linq连接两个表.
表名称是MapAssets和ExitPoint.
在数据库中,它们与有关系"相关

ASP.NET 3.5 C#
I am joining two tables using Linq.
Table names are MapAssets and ExitPoint.
In Database they are related with 'has a relationship'

我正在BLL中编写一个函数以返回联接表

I am writing a function in my BLL to return the joined table

        public List<ExitPoints> GetExitPointDetailsByProjectID(int iProjectID)
        {
            ctx = new CoreDBDataContext();
            var exitPointDetails = from ma in ctx.MapAssets
                                   join ep in ctx.ExitPoints
                                   on ma.MapAssetID equals ep.MapAssetID
                                   where ma.ProjectID == iProjectID
                                   select new
                                   {
                                       //would like to have data from both tables here
                                       ctx.MapAssets,
                                       ctx.ExitPoints
                                   };
            return exitPointDetails.ToList();
        }

这显然是行不通的.而且我根本不知道要返回什么.
我要返回的所有约束都是能够绑定到gridview.
这是正确的方法吗?否则正确的方法是什么?

This obviuosly doesn't work. And I dont know what to return at all.
All constraint I have for the return is to be able to be bound to a gridview.
is this the correct way? Or else whats the correct way?

推荐答案

您不能,或者更好的方法是,将它们装回objectList中装箱,但这会使事情变得非常复杂,因为您不能将它们转换为任何类型(当然是匿名的),并且只能通过反射来访问它们的属性....

You can't, or better, the only way is to return them boxed in a List of object, but this hugely complicates things, because you can't cast them to any type (of course it's anonymous) and you can only access their properties through reflection....

在这种情况下,我强烈建议您创建一个自定义类.

In cases like that, I'd highly suggest you to create a custom class.

旁注...
如果您使用的是.net 4,则事情会更容易,因为您可以返回 dynamic键入而不是object(请查看此 链接 查看dynamic的简化),但无论如何我还是希望创建一个自定义类.

On a side note...
If you were using .net 4, things would be easier because you could returns dynamic Type instead of object (look at this link to see dynamic's simplifications), but I'd prefer to create a custom class anyway.

这篇关于如何返回Generic.List&lt; Anonymoustype&gt;从C#中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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