从函数返回匿名类型

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

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

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

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

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

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

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

 private List 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(); } 

不,您不能直接返回匿名类型,但可以使用即兴界面返回它。 像这样的东西:

 public interface IMyInterface { string GroupName { get; } int RowSpan { get; } } private IEnumerable GetRowGroups() { var list = from item in table select new { GroupName = groupedTable.Key.column1, RowSpan = groupedTable.Count() } .ActLike(); return list; } 

只需使用和ArrayList

  public static ArrayList GetMembersItems(string ProjectGuid) { ArrayList items = new ArrayList(); items.AddRange(yourVariable .Where(p => p.yourproperty == something) .ToList()); return items; } 

使用object ,而不是var 。 但是,您必须使用reflection来访问匿名类型范围之外的属性。

 private object GetRowGroups(string columnName) ... var RowGroupList = new List(); ... 

返回一个元组,C#7function。 你可以在这里阅读更多内容: https : //blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/