2011-09-21 112 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; 
    }