我有以下内容:
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 :(得分: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
});
在我看来你想要什么。
您可以使用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);
}
}
}