将IEnumerable<T>项目添加到IEnumerable<T>中。

6

我有以下内容:

 foreach (var item in selected)
 {
    var categories = _repo.GetAllDCategories(item);
    var result = from cat in categories
                 select
                     new
                     {
                        label = cat.Name,
                        value = cat.Id
                     };
}

方法GetAllDCategories返回一个IEnumerable<T>

如何将result添加到新的IEnumerable对象中,该对象将包含循环中所选项的result中的所有项目?


你不能向现有的 IEnumerable 添加任何内容 -> 它是只读集合! - bash.d
2
您可以使用扩展方法Concat来连接两个IEnumerable。 - Fabio Marcolini
3个回答

14

你能不能不使用Concat

用类似下面的方法:

        IEnumerable<string> s1 = new List<string>
                                    {
                                        "tada"
                                    };
        IEnumerable<string> s2 = new List<string>
                                    {
                                        "Foo"
                                    };
        s1 = s1.Concat(s2);

+1 连接很好,另外 OP 可能想要连接多个类似于 King King SelectMany(+1)。 - Alexei Levenkov
2
我认为这是对问题的错误理解。 - Jodrell

3
var result = selected.Select(item=>_repo.GetAllDCategories(item))
                     .SelectMany(x=>x,(x,cat)=> select new {
                                                   label = cat.Name, 
                                                   value = cat.Id
                                                });

出现了错误:“无法从用法中推断出方法‘IEnumerable<TResult> System.Linq.Enumerable.SelectMany<TSource, TResult>(this IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>)'的类型参数。请尝试明确指定类型参数。”我已经明确指定了类型,但仍然不起作用! - SVI

1

好的,我认为这里有些混淆。

var result = selected.SelectMany(item => 
    _repo.GetAllDCategories(item).Select(cat =>
        new
        {
            Label = cat.Name,
            Value = cat.Id
        });

在我看来,你想要的是。

你可以使用 SelectMany 来将 IEnumerable<IEnumerable<T>> “压缩”或“展开”成一个 IEnumerable<T>

这类似于拥有一个这样的函数

IEnumerable<KeyValuePair<string, int>> GetSelectedCategories(
        IEnumerable<string> selected)
{
    foreach (var item in selected)
    {
        foreach (var category in _repo.GetAllDCategories(item))
        {
            yield return new KeyValuePair<string, int>(
                category.Name,
                category.Id);
        }
    }
}

谢谢!那就是我所谓的读取和回答问题的天才方式。完美! - SVI

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接