1

I have the below code that uses yield to build a collection:

public IEnumerable<Comment> GetComments(
    IEnumerable<ContentItem> commentContentItems)
{

    foreach (var commentContentItem in commentContentItems)
    {
        var Comment = new Comment
            {
                CommentCreatedByName = commentContentItem.InitiatorName,
                CommentCreatedByID = commentContentItem.CreatedByID,
                ContentItemID = commentContentItem.ContentItemID,
                CommentDate = commentContentItem.CreatedDate
            };

        yield return Comment;
    }
}

I want to start checking if an item is deleted and, if so, yield in such a way as it won't add the deleted item to the collection.

I know I could use linq to reduce the set like this:

foreach (var commentContentItem in commentContentItems.Where(x => !x.Deleted))

But for arguments sake; how would you do this using yield for, let's say, situations where yield is more performant?

eg:

if (commentContentItem.Deleted)
{
    yield return null;
}
4

2 回答 2

11

我是否正确,您只是不想在结果中删除项目?那就不要yield return在那种情况下!

if (!commentContentItem.Deleted)
    yield return Comment;
于 2013-09-12T09:46:53.807 回答
4

我建议你在Select这里使用,它更简单

public IEnumerable<Comment> GetComments(
    IEnumerable<ContentItem> commentContentItems)
{
    return commentContentItems.Where(x=>!x.IsDeleted).Select(x=>new new Comment
            {
                CommentCreatedByName = x.InitiatorName,
                CommentCreatedByID = x.CreatedByID,
                ContentItemID = x.ContentItemID,
                CommentDate = x.CreatedDate
            });
}

它的工作原理相同,看起来更干净。它将完成这项工作并返回不包含已删除项目的 IEnumerable。

这是一个XY问题,我认为改进解决方案是更好的主意。

于 2013-09-12T09:51:17.410 回答