将IEnumerable <t>项添加到IEnumerable <t> </t> </t>

时间:2013-08-20 08:20:23

标签: 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
                     };
}

方法GetAllDCategories会返回IEnumerable<T>

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

3 个答案:

答案 0 :(得分:4)

你能否使用Concat

这样的东西
        IEnumerable<string> s1 = new List<string>
                                    {
                                        "tada"
                                    };
        IEnumerable<string> s2 = new List<string>
                                    {
                                        "Foo"
                                    };
        s1 = s1.Concat(s2);

答案 1 :(得分:2)

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

答案 2 :(得分:1)

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

var result = selected.SelectMany(item => 
    _repo.GetAllDCategories(item).Select(cat =>
        new
        {
            Label = cat.Name,
            Value = cat.Id
        });
在我看来你想要什么。

您可以使用SelectManyIEnumerable<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);
        }
    }
}