C# 添加IEnumerable<;T>;要添加到IEnumerable的项<;T>;
我有以下资料:C# 添加IEnumerable<;T>;要添加到IEnumerable的项<;T>;,c#,linq,ienumerable,C#,Linq,Ienumerable,我有以下资料: foreach (var item in selected) { var categories = _repo.GetAllDCategories(item); var result = from cat in categories select new { label = cat.Name,
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
如何将result
添加到新的IEnumerable
对象中,该对象将包含循环中所有选定项的result
中的所有项?您不能使用吗
差不多
IEnumerable<string> s1 = new List<string>
{
"tada"
};
IEnumerable<string> s2 = new List<string>
{
"Foo"
};
s1 = s1.Concat(s2);
IEnumerable s1=新列表
{
“塔达”
};
IEnumerable s2=新列表
{
“福”
};
s1=s1。混凝土(s2);
嗯,我想这里有些混乱
var result = selected.SelectMany(item =>
_repo.GetAllDCategories(item).Select(cat =>
new
{
Label = cat.Name,
Value = cat.Id
});
我觉得你想要什么
您可以使用将IEnumerable
压缩或“展平”为IEnumerable
它类似于具有这样的功能
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);
}
}
}
IEnumerable GetSelectedCategories(
IEnumerable(已选定)
{
foreach(所选中的var项目)
{
foreach(回购GetAllDCategories(项目)中的var类别)
{
返回新的KeyValuePair(
类别,名称,,
类别(Id);
}
}
}
您不能将任何内容添加到现有的IEnumerable
->它是一个只读集合!您可以使用扩展方法Concat连接两个ienumerable+1 Concat很好,而且OP可能想要Concat多个类似于King King SelectMany(+1)的答案。我认为这是对问题的误读。给出了方法“ienumerable System.Linq.Enumerable.SelectMany”(this ienumerable,Func)的类型参数无法从用法中推断。请尝试显式指定类型参数。我已显式放置了类型,但不起作用!谢谢这就是我所说的阅读和回答问题的天才方式。完美的
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);
}
}
}