Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding element to IEnumerable<IPublishedContent>

I have two IEnumerable objects, if a specific condition is met, i need to take each element from first IEnumerable to second IEnumerable. My code is like this

IEnumerable<IPublishedContent> nodesTemp = posts.Take(10).ToList();
IEnumerable<IPublishedContent> nodes = null;
foreach (var n in nodesTemp)
{
    if (condition=true)
    {
        nodes.add(n);           
    }
}

But this throws an error

: '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;
            }
        }

    }
}
like image 273
None Avatar asked May 21 '26 14:05

None


1 Answers

You can't do this. The reason is because IEnumerable just represents iterator over some collection. It can be array in memory, select from remote database, or even constant call like this:

IEnumerable<int> GetSomeConsts()
{
    yield return 1;
    yield return 101;
    yield return 22;
}

What you can do is to expand post iterator of your first collection. For example like this:

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;
}

Then just call it like this:

var nodes = posts.Take(count).Where(IsCondition);
like image 171
eocron Avatar answered May 24 '26 04:05

eocron