Return Anonymous Type from a function

前端 未结 6 1004
庸人自扰
庸人自扰 2020-12-16 11:05

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 fiel

6条回答
  •  清酒与你
    2020-12-16 12:00

    From C#7 you can return a list of tuples:

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

    You can even give the members of the tuple names:

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

    However you need System.ValueTuple from the Nuget Package Manager.

    Anyway I suggest to give things a clear name that includes what their purpose is, in particular when this is part of a public API. Having said this you should consider to create a class that holds those properties and return a list of that type.

提交回复
热议问题