无法从使用中推断出SelectMany
我尝试编译代码时收到以下错误:
无法从用法中推断出方法’System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable,System.Func>)’的类型参数。 尝试显式指定类型参数。
List entries = ... List arguments = ... var argumentsVal = entries.SelectMany((RowEntry entry) => (IEnumerable)arguments.SelectMany((RowArgument arg) => new RowArgumentVal() { Action = "X" , EntryID = entry.ID , ArgID = arg.ID , Val_BIT = true , Val_DATE = new DateTime(2014, 01, 04) , Val_DATETIME = new DateTime(2014, 01, 04) , Val_DECIMAL = 4.6M , Val_INT = 88 , Val_TIME = new TimeSpan(6, 0, 0) } ).Cast()).Cast().ToList();
我不知道如何能够进一步“打字”这个……
问题是内部SelectMany
不适用于那里,你可能意味着Select
。
var argumentsVal = entries.SelectMany(entry => arguments.Select(arg => new RowArgumentVal())).ToList();
每个entry
将根据arguments
映射到IEnumerable
。
想象一下外部SelectMany
是一个简单的Select
,它会生成List
。 但由于它是SelectMany
,它会将结果“展平”为一个简单的List
。
SelectMany
方法需要映射到IEnumerable
– 而不是T
如果RowArgumentVal
碰巧实现了IEnumerable
接口,那么原始代码将是有效的,我认为不是这种情况。
这似乎是两个列表中的笛卡尔积,因为它们之间没有关系。 你可能想加入它们,但目前还不清楚如何。
以下是生成笛卡尔积的更具可读性和编译方式:
var query = from entry in entries from argument in arguments select new RowArgumentVal { Action = "X", EntryID = entry.ID, ArgID = argument.ID, // ... }; List argumentsVal = query.ToList();
如果您想要笛卡尔积,请尝试执行以下操作
var argumentsVal = from e in entries from a in arguments select new RowArgumentVal(...)
顺便说一下,你可以做的“进一步输入”就是给generics方法调用提供类型参数。 特别是,如果您已将第二个SelectMany
更改为SelectMany
您将获得错误
无法将类型
RowArgumentVal
隐式转换为System.Collections.Generic.IEnumerable
。 存在显式转换(您是否错过了演员?)无法将lambda表达式转换为委托类型
System.Func
因为块中的某些返回类型不能隐式转换为委托返回类型>
这可能会引导你到这里的其他答案 – 你试图调用一个预期序列的方法,但你给它一个单独的对象。
(或者在尝试确定要添加的类型参数时,您会更快意识到错误。)