简体   繁体   中英

.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?

(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...)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM