3 ms·
I like to return IEnumerable instead of List<>: IEnumerable<Product> GetExclusiveProducts(List<Product> source) => source .Where(p => p
by shortrounddev2 1y ago
I like to return IEnumerable instead of List<>:
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 this
Also 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
- mlhpdx 1y agoGiven the use case I’d consider IGrouping<PhoneType,Product>. My point being LINQ is a wide subject and most code I see barely touches the surface.
- nlawalker 1y agoThe only problem with IEnumerable's open-endedness is that it's so open-ended. It makes no implicit guarantees about order, finiteness, side effects, speed/efficiency, idempotency etc. It's easy to assume those things until you accidentally find a situation where one or more are not in your favor.
- pjc50 1y agoThis is generally better yes, especially if it's going to end up inside another LINQ operation - you can avoid materializing the list. 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
- jayd16 1y agoIt really depends. IEnumerable could have a lambda that leaks the world and makes a web call on every iteration for all the caller knows. You know iterating a List will be fairly banal. 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.