将 IEnumerable<T> 项添加到 IEnumerable<T>

SVI*_*SVI 2 c# linq ienumerable

我有以下几点:

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

该方法GetAllDCategories返回一个IEnumerable<T>

如何添加resultIEnumerable包含result循环中所有选定项目的所有项目的新对象?

Adr*_*der 9

你不能使用 Concat吗?

就像是

        IEnumerable<string> s1 = new List<string>
                                    {
                                        "tada"
                                    };
        IEnumerable<string> s2 = new List<string>
                                    {
                                        "Foo"
                                    };
        s1 = s1.Concat(s2);
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是对问题的误读。 (2认同)

Jod*_*ell 1

嗯,我认为这里有些混乱,

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

在我看来你想要什么。

您可以使用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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)