从函数返回匿名类型

Dko*_*ong 21 c# linq generics collections

我可以在函数中使用匿名类型作为返回类型,然后将返回值的内容填充到某种数组或集合中,同时还向新数组/集合添加其他字段吗?请原谅我的伪代码......

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"));

}
Run Code Online (Sandbox Code Playgroud)

ada*_*ost 16

不,您无法从该方法返回匿名类型.有关详细信息,请阅读 MSDN文档.使用classstruct代替anonymous类型.

你应该阅读博客文章 - 可怕的grotty hack:返回一个匿名类型的实例

如果您使用的是框架4.0,则可以返回,List<dynamic>但要小心访问匿名对象的属性.

private List<dynamic> 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.ToList<dynamic>();
}
Run Code Online (Sandbox Code Playgroud)


mel*_*okb 16

这是一个非常受欢迎的问题.通常,由于需要强类型,因此无法返回匿名类型.但是有一些解决方法.

  1. 创建一个简单类型来表示返回值.(见这里这里).通过使用生成简化.
  2. 创建一个帮助方法,使用示例实例进行转换以转换为匿名类型.

  • 请始终引用外部链接的小片段.在这种情况下,第一个被打破,所以你的答案是无用的. (2认同)
  • @mellamokb,除了 OP 之外的人都将这个结果显示为他们的热门谷歌点击之一,因此将每个未来用户重定向回谷歌是完全没有帮助的。感谢您努力回答,但请在答案中内嵌重要信息,或者如果您只是重新指向其他资源,请发表评论。 (2认同)