2013-08-20 58 views
0

我有以下幾點:添加了IEnumerable <T>項目的IEnumerable <T>

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所有項目的所有循環中的選定項目?

+0

不能添加任何東西,現有'IEnumerable'->它是一個只讀集合! –

+0

任何其他解決方案? – SVI

+1

你可以使用擴展方法Concat連接兩個枚舉 –

回答

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); 
     } 
    } 
} 
+0

謝謝!這就是我稱之爲閱讀和回答問題的天才方式。完善! – SVI

4

你不能使用Concat

喜歡的東西

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

+1 Concat很好,也可能OP想要連接多個類似於King King SelectMany(+ 1)的答案。 –

+1

我認爲這是對這個問題的誤讀。 – Jodrell

+0

謝謝@Jodrell +1 – SVI

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

給出一個錯誤'方法的類型參數'IEnumerable System.Linq.Enumerable.SelectMany (此IEnumerable ,Func >)'不能從用法。嘗試明確指定類型參數。「我已經明確地指定了類型,但沒有工作! – SVI

相關問題