2

我有以下内容:

 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新对象?IEnumerableresult

4

3 回答 3

9

你不能使用 Concat吗?

就像是

        IEnumerable<string> s1 = new List<string>
                                    {
                                        "tada"
                                    };
        IEnumerable<string> s2 = new List<string>
                                    {
                                        "Foo"
                                    };
        s1 = s1.Concat(s2);
于 2013-08-20T08:23:27.250 回答
2
var result = selected.Select(item=>_repo.GetAllDCategories(item))
                     .SelectMany(x=>x,(x,cat)=> select new {
                                                   label = cat.Name, 
                                                   value = cat.Id
                                                });
于 2013-08-20T08:24:10.210 回答
1

好吧,我认为这里有些混乱,

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

在我看来你想要什么。

您可以使用SelectMany“压扁”或“压平” anIEnumerable<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);
        }
    }
}
于 2013-08-20T08:37:19.523 回答