IEnumerable vs IReadonlyCollection vs ReadonlyCollection for exposing a list member

One important aspect seems to be missing from the answers so far: When an IEnumerable<T> is returned to the caller, they must consider the possibility that the returned object is a “lazy stream”, e.g. a collection built with “yield return”. That is, the performance penalty for producing the elements of the IEnumerable<T> may have to … Read more

How to loop through IEnumerable in batches [duplicate]

You can use MoreLINQ’s Batch operator (available from NuGet): foreach(IEnumerable<User> batch in users.Batch(1000)) // use batch If simple usage of library is not an option, you can reuse implementation: public static IEnumerable<IEnumerable<T>> Batch<T>( this IEnumerable<T> source, int size) { T[] bucket = null; var count = 0; foreach (var item in source) { if (bucket … Read more

How to sort an IEnumerable

The same way you’d sort any other enumerable: var result = myEnumerable.OrderBy(s => s); or var result = from s in myEnumerable orderby s select s; or (ignoring case) var result = myEnumerable.OrderBy(s => s, StringComparer.CurrentCultureIgnoreCase); Note that, as is usual with LINQ, this creates a new IEnumerable<T> which, when enumerated, returns the elements of … Read more

Why does this string extension method not throw an exception?

You are using yield return. When doing so, the compiler will rewrite your method into a function that returns a generated class that implements a state machine. Broadly speaking, it rewrites locals to fields of that class and each part of your algorithm between the yield return instructions becomes a state. You can check with … Read more

What is the difference between IEnumerator and IEnumerable? [duplicate]

IEnumerable is an interface that defines one method GetEnumerator which returns an IEnumerator interface, this in turn allows readonly access to a collection. A collection that implements IEnumerable can be used with a foreach statement. Definition IEnumerable public IEnumerator GetEnumerator(); IEnumerator public object Current; public void Reset(); public bool MoveNext(); example code from codebetter.com

Convert from List into IEnumerable format

You don’t need to convert it. List<T> implements the IEnumerable<T> interface so it is already an enumerable. This means that it is perfectly fine to have the following: public IEnumerable<Book> GetBooks() { List<Book> books = FetchEmFromSomewhere(); return books; } as well as: public void ProcessBooks(IEnumerable<Book> books) { // do something with those books } which … Read more