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"));
}
ada*_*ost 16
不,您无法从该方法返回匿名类型.有关详细信息,请阅读此 MSDN文档.使用class或struct代替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>();
}