2011-09-21 256 views
13

我可以在函数中使用匿名类型作为返回类型,然后将值返回给某个数组或集合中的某种东西,同时还将新的字段添加到新的数组/集合中?原谅我...伪返回匿名类型从函数

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

} 
+0

的可能重复的[访问C#匿名类型对象(http://stackoverflow.com/questions/713521/accessing-c-sharp -anonymous-type-objects) – nawfal

+0

[Return anonymous type?]可能重复(http://stackoverflow.com/questions/534690/return-anonymous-type) –

回答

11

这是一个very popular question。一般来说,由于强打字的要求,你不能返回一个匿名类型。但是有几个解决方法。

  1. 创建一个简单的类型来表示返回值。 (见herehere)。通过generating from usage简化操作。
  2. 使用示例实例创建一个帮助方法,以cast to the anonymous type进行强制转换。
+1

请始终引用外部链接的一小段代码。在这种情况下,第一个是坏的,所以你的答案是无用的。 – Teejay

+0

“使用中产生”链接中断 – dlchambers

+0

@dlchambers:谢谢。我改变了链接以使用wayback机器中的档案。 – mellamokb

12

不,你不能返回从方法匿名类型。欲了解更多信息,请阅读this MSDN文档。使用classstruct而不是anonymous类型。如果您使用的框架4.0,那么你可以返回List<dynamic>但要小心访问匿名对象的属性Horrible grotty hack: returning an anonymous type instance

-

你应该阅读博客文章。

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

不,您不能直接返回匿名类型,但可以使用impromptu interface返回。事情是这样的:

public interface IMyInterface 
{ 
    string GroupName { get; } 
    int RowSpan { get; } 
} 

private IEnumerable<IMyInterface> GetRowGroups() 
{ 
    var list = 
     from item in table 
     select new 
     { 
      GroupName = groupedTable.Key.column1, 
      RowSpan = groupedTable.Count() 
     } 
     .ActLike<IMyInterface>(); 

    return list; 
} 
+1

可爱,但是我不太确定这是否比制作具体类型更容易...(IDE中的工具可以帮助) – 2011-09-21 03:10:12

1

使用object,不var。尽管如此,您将不得不使用反射来访问匿名类型范围之外的属性。

private object GetRowGroups(string columnName) 
... 
var RowGroupList = new List<object>(); 
... 
+0

这可以稍后通过'dynamic'(C#4)来访问......但是它会失去所有实用的安全性。 – 2011-09-21 03:12:20

2

只需使用和ArrayList

public static ArrayList GetMembersItems(string ProjectGuid) 
    { 
     ArrayList items = new ArrayList(); 

       items.AddRange(yourVariable 
         .Where(p => p.yourproperty == something) 
         .ToList()); 
      return items; 
    }