本文介绍了无法从用法推断出SelectMany的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试编译代码时,出现以下错误:

I get the following error when I try to compile my code:

        List<RowEntry> entries = ...
        List<RowArgument> arguments = ...

        var argumentsVal = entries.SelectMany((RowEntry entry) =>
            (IEnumerable<RowArgumentVal>)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<RowArgumentVal>()).Cast<RowArgumentVal>().ToList();

我不知道该如何进一步键入" ...

I don't get how I can "type" this even further...

推荐答案

问题是内部的SelectMany不适用于该位置,您可能是指Select.

The problem is that the inner SelectMany isn't applicable there, and you probably meant Select.

var argumentsVal = entries.SelectMany(entry =>
    arguments.Select(arg => new RowArgumentVal())).ToList();

每个entry将根据arguments映射到IEnumerable<RowArgumentVal>.

想象一下,外部SelectMany是一个简单的Select,它将生成List<IEnumerable<RowArgumentVal>>.但是因为它是SelectMany,它将把结果展平"为简单的List<RowArgumentVal>.

Imagine the outer SelectMany was a simple Select, and it would generate List<IEnumerable<RowArgumentVal>>. But because it is SelectMany, it will "flatten" the result into a simple List<RowArgumentVal>.

SelectMany方法期望映射到IEnumerable<T>-而不是T.如果RowArgumentVal恰好实现了IEnumerable<T>接口,那么您的原始代码将是有效的,但我认为情况并非如此.

The SelectMany method expects a mapping to IEnumerable<T> - not T. Your original code would be valid if RowArgumentVal just happened to implement the IEnumerable<T> interface, which I suppose isn't the case.

这篇关于无法从用法推断出SelectMany的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 12:40