.net collections optimization

I'm not really experienced in .Net Collections.

Here I have the code I would like to rewrite somehow.

emptyOrganization.Name = "";
var organizations = new List<IOrganization>();
organizations.Add(emptyOrganization);
organizations.AddRange(_organizationRepository.GetAll(LanguageCurrent.Id));
model.Organizations = organizations;

Can this be rewritten in fewer lines?

Jon Skeet
people
quotationmark

(I'm assuming that emptyOrganization is an IOrganization and that GetAll returns an IEnumerable<IOrganization> or something similar...)

Your code is already efficient, but you might want to try to make it clearer. You could use:

model.Organizations = new[] { emptyOrganization }
    .Concat(_organizationRepository.GetAll(LanguageCurrent.Id))
    .ToList();

If you regularly find yourself wanting a collection which is one value followed by the values from another collection, you could always write an extension method for that:

public static IEnumerable<T> Prepend(this IEnumerable<T> source, T value)
{
    yield return value;
    foreach (var item in source)
    {
        yield return item;
    }
}

Then you'd have:

model.Organizations = _organizationRepository.GetAll(LanguageCurrent.Id)
   .Prepend(emptyOrganization)
   .ToList();

... which is perhaps the most expressive form. (Prepend is also part of MoreLINQ, so you don't actually have to write it yourself...)

people

See more on this question at Stackoverflow