How to get an empty collection list?

I have a collection of an anonymous class and I want to return an empty list.

What is the best readable expression used?

I, however, come from the following, but I do not think they are readable enough:

var result = MyCollection.Take(0).ToList(); var result = MyCollection.Where(p => false).ToList(); 

Note. I do not want to clear the collection.

Any suggestion!

+6
source share
4 answers

What about:

 Enumerable.Empty<T>(); 

This returns an empty list that is of type T. If you really need a List so you can do this:

 Enumerable.Empty<T>().ToList<T>(); 
+31
source

In fact, if you use a universal extension, you don’t even need to use Linq for this, you already have an anonymous type open via T

 public static IList<T> GetEmptyList<T>(this IEnumerable<T> source) { return new List<T>(); } var emp = MyCollection.GetEmptyList(); 
+10
source

Given that your first sentence works and should work well - if readability is the only problem, why not create an extension method:

 public static IList<T> CreateEmptyCopy(this IEnumerable<T> source) { return source.Take(0).ToList(); } 

Now you can reorganize your example into

 var result = MyCollection.CreateEmptyCopy(); 
+9
source

For performance reasons, you should stick with the first option you come across.

Another will iterate over the entire collection before returning an empty list.

Since there is no anonymous type in the source code to create a list. However, it is possible to create such a list through reflection.

+6
source

Source: https://habr.com/ru/post/886227/


All Articles