从函数返回匿名类型 [英] Return Anonymous Type from a function

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

问题描述

我可以使用匿名类型作为函数的返回类型,然后东西,返回值转换成某种类型的数组或集合,同时还增加了一个附加的字段到新阵列/收藏?原谅我...伪代码

 私人变种GetRowGroups(字符串COLUMNNAME)
{
VAR groupQuery =从表_dataSetDataTable.AsEnumerable()
组表被新{COLUMN1 =表[COLUMNNAME]}
到groupedTable
选择新的
{
组名= groupedTable.Key。 COLUMN1,
ROWSPAN = groupedTable.Count()
};
返回groupQuery;

}

私人无效CreateListofRowGroups()
{
变种RowGroupList =新的List<&???? GT;();
RowGroupList.Add(GetRowGroups(COL1));
RowGroupList.Add(GetRowGroups(COL2));
RowGroupList.Add(GetRowGroups(COL3));

}


解决方案

这是一个的很受欢迎的问题。一般来说,你不能匿名类型由于强类型的要求回报。然而,有一对夫妇的解决方法。




  1. 创建一个简单的类型来表示的返回值。 (请参见 href=\"http://stackoverflow.com/questions/534690/linq-to-sql-return-anonymous-type\">和的这里)。使简单以从使用中产生

  2. 创建一个帮手方法转换为匿名类型使用铸造样本实例。


Can I use an anonymous type as a return type in a Function, and then stuff that returned value into an array or collection of some sort whilst also adding an additional field to the new array/collection? excuse my pseudocode...

private var GetRowGroups(string columnName)
{
var groupQuery = from table in _dataSetDataTable.AsEnumerable()
                             group table by new { column1 = table[columnName] }
                                 into groupedTable
                                 select new
                                 {
                                     groupName = groupedTable.Key.column1,
                                     rowSpan = groupedTable.Count()
                                 };
    return groupQuery;

}

private void CreateListofRowGroups()
{
    var RowGroupList = new List<????>();
    RowGroupList.Add(GetRowGroups("col1"));
    RowGroupList.Add(GetRowGroups("col2"));
    RowGroupList.Add(GetRowGroups("col3"));

}

解决方案

This is a very popular question. In general you cannot return an anonymous type due to the requirement of strong typing. However there are a couple of workarounds.

  1. Create a simple type to represent the return value. (See here and here). Make it simple by generating from usage.
  2. Create a helper method to cast to the anonymous type using a sample instance for casting.

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

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