c# - 将元素添加到 IEnumerable<IPublishedContent>

标签 c# asp.net linq generics

我有两个 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/

相关文章:

c# - 在 asp.net 应用程序中编辑/删除导航栏

c# - .NET 4.0 到 4.5 迁移并在 4.0 机器上运行异常

c# - 如何使用 SpecFlow 设置个人跟踪/日志记录

c# - 在经典 ASP 上构建 .net 应用程序

c# - ASP.NET 无法在同一类型变量中转换 session 变量

asp.net - 有没有办法知道 session 使用了多少 RAM?

c# - 在列表列表中查找项目

c# - 提高 LINQ 性能

c# - 如果 Linq 查询为 Null,则返回 System.Int32.MinValue

c# - 如何在 Unity 3d 中使用 JSON Web Token (JWT)?