by shortrounddev2 · 1y ago · 0 comments
IEnumerable<Product> GetExclusiveProducts(List<Product> source) =>
source
.Where(p => p.ProductTitle == "iPhone")
.OrderBy(p => p.TypeOfPhone);
That way the user can decide if they want a List or Array or Set or whatever, and you can also add additional queries to thisAlso better to pass IEnumerable to the function instead of List, for the same reasons
Also I forget the syntax but you can use an extension method to add it to linq I think
So from an API perspective, I think returning IEnumerables can end up being too cute. The caller has to deal with this unknown thing.
In general you should be clear about what you return and loose about what you accept. If your whole API is returning IEnumerables and some are expensive to iterate and others are not its actually less clear what I'm getting. And this isn't to say List is always the answer either.
Cases where it isn't:
- risk of multiple execution (there is a CA warning for this)
- when returning data protected by a mutex, you should always materialize a copy of the returned list/array rather than return an enumerable