FindAll, ConvertAll are your friends

Let’s take a look at following code:

public List<string> GetDeleteWarnings_ForEach()
{
    List<string> messages = new List<string>();
    foreach (ItemReference reference in _itemReferences)
    {
        if (!reference.CanBeDeleted)
        {
            messages.Add(reference.DeleteMessage);
        }
    }
    return messages;
}

Using FindAll and ConvertAll you can do it in one, very obvious, line:

public List<string> GetDeleteWarnings_Fluently()
{
    return _itemReferences
        .FindAll(x => !x.CanBeDeleted)
        .ConvertAll(x => x.DeleteMessage);
}

Tags:

Questions?

Consider using our Q&A forum for asking questions.