我有两个 IEnumerable 对象,如果满足特定条件,我需要将每个元素从第一个 IEnumerable 获取到第二个 IEnumerable。我的代码是这样的
IEnumerable<IPublishedContent> nodesTemp = posts.Take(10).ToList();
IEnumerable<IPublishedContent> nodes = null;
foreach (var n in nodesTemp)
{
if (condition=true)
{
nodes.add(n);
}
}
但这会引发错误
: 'System.Collections.Generic.IEnumerable<Umbraco.Core.Models.IPublishedContent>' does not contain a definition for 'add' and no extension method 'add' accepting a first argument of type 'System.Collections.Generic.IEnumerable<Umbraco.Core.Models.IPublishedContent>' could be found (are you missing a using directive or an assembly reference?)
Complete code for reference
IEnumerable<IPublishedContent> nodesTemp = posts.Take(count).ToList();
IEnumerable<IPublishedContent> nodes = null;
foreach (IPublishedContent n in nodesTemp)
{
var rolename = n.GetProperty("focusedUserGroup").Value.ToString();
var username = umbraco.cms.businesslogic.member.Member.GetCurrentMember().Text;
var flag = false;
if (!string.IsNullOrEmpty(rolename))
{
var groups = rolename.Split(',');
foreach (var group in groups)
{
if (Roles.IsUserInRole(username, group))
{
nodes.add(n);
break;
}
}
}
}
最佳答案
你不能这样做。原因是因为 IEnumerable 只是表示某个集合上的迭代器。它可以是内存中的数组,从远程数据库中选择,甚至是像这样的常量调用:
IEnumerable<int> GetSomeConsts()
{
yield return 1;
yield return 101;
yield return 22;
}
您可以做的是扩展第一个集合的后迭代器。例如像这样:
bool IsCondition(IPublishedContent n)
{
var rolename = n.GetProperty("focusedUserGroup").Value.ToString();
var username = umbraco.cms.businesslogic.member.Member.GetCurrentMember().Text;
if (!string.IsNullOrEmpty(rolename))
{
var groups = rolename.Split(',');
foreach (var group in groups)
{
if (Roles.IsUserInRole(username, group))
{
return true;
}
}
}
return false;
}
然后就这样调用它:
var nodes = posts.Take(count).Where(IsCondition);
关于c# - 将元素添加到 IEnumerable<IPublishedContent>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39866872/