如何为匿名对象指定Func签名?new Func<DataSet, **IEnumerable<int>>**我在Func声明中将返回类型指定为IEnumerable 时遇到麻烦我从表达式中得到的错误是 无法将表达式类型'System.Collections.Generic.IEnumerable '转换为返回类型'System.Collections.Generic.IEnumerable'如何在func中指定IEnumerable ? public int GetCachedRootNodeId(IList<int> fromNodeIds, int forNodeId) { var result = forNodeId; const string spName = "spFetchAllParentNodeIDs"; using (var ds = _df.ExecuteDatasetParamArray(_ConnectionString, spName, forNodeId)) { if (DataAccessUtil.DataSetIsEmpty(ds)) return result; var orderByLevelDesc = new Func<DataSet, IEnumerable<int>>(resultSet => from DataRow row in DataAccessUtil.GetFirstTableRows(resultSet) orderby DataAccessUtil.GetInt32(row, "Level") descending select new { ParentNodeId = DataAccessUtil.GetInt32(row, "ParentNodeID") }); //// Get top-most parent's node ID first (higher the level, the more top-most the parent is) //var query = from DataRow row in DataAccessUtil.GetFirstTableRows(ds) // orderby DataAccessUtil.GetInt32(row, "Level") descending // select new { ParentNodeId = DataAccessUtil.GetInt32(row, "ParentNodeID") }; //foreach (var nodeInfo in query) foreach (var nodeInfo in orderByLevelDesc(ds)) { if (fromNodeIds.Contains(nodeInfo.ParentNodeId)) return nodeInfo.ParentNodeId; } } return result; }顺便说一句,我可以使用注释的代码“查询”并完成它。但希望表现得更好,并在查看此答案后尝试新的东西Why doesn't C# have lexically nested functions?编辑:最终结果 public int GetCachedRootNodeId(IList<int> fromNodeIds, int forNodeId) { var result = forNodeId; const string spName = "spFetchAllParentNodeIDs"; using (var ds = _df.ExecuteDatasetParamArray(_ConnectionString, spName, forNodeId)) { if (DataAccessUtil.DataSetIsEmpty(ds)) return result; var orderParentNodeIDByLevelDesc = new Func<DataSet, IEnumerable<int>>(resultSet => from DataRow row in DataAccessUtil.GetFirstTableRows(resultSet) orderby DataAccessUtil.GetInt32(row, "Level") descending select DataAccessUtil.GetInt32(row, "ParentNodeID")); foreach (var parentNodeId in orderParentNodeIDByLevelDesc(ds)) { if (fromNodeIds.Contains(parentNodeId)) return parentNodeId; } } return result; } 最佳答案 在这种情况下,您真正想要的就是int ...,因此只需将您的选择更改为:select DataAccessUtil.GetInt32(row, "ParentNodeID"));并将您的foreach更改为:foreach (var nodeInfo in orderByLevelDesc(ds)){ if (fromNodeIds.Contains(nodeInfo)) return nodeInfo;}关于c# - 如何使用Func <T,Q>在Linq中指定.NET匿名对象返回类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/596465/ 10-17 00:42