Reputation: 81
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?
Upvotes: 0
Views: 118
Reputation: 17845
Without using Linq, you can save one line by initializing your collection with the empty organisation:
var organizations = new List<IOrganization> {emptyOrganization};
organizations.AddRange(_organizationRepository.GetAll(LanguageCurrent.Id));
Upvotes: 0
Reputation: 460108
If you really want to use a one liner you could use LINQ:
model.Organizations = new IOrganization[]{ emptyOrganization }
.Concat(_organizationRepository.GetAll(LanguageCurrent.Id))
.ToList();
But why do you want that? Your code is readable and efficient.
Upvotes: 2
Reputation: 1500465
(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...)
Upvotes: 6