Return maximum LINQ items

Suppose I have a search module with a basic data repository and a requirement to return a maximum of 25 search query results. I can accomplish this using the Take () operation:

IEnumerable<Contact> Search(string name) { // validation/cleanup on name parameter IEnumerable<Contact> matching = _repository.Search(name); return matching.Take(25); } 

Then, suppose I have an additional requirement to throw an exception if more than 25 results are returned (i.e. the search parameter is too wide). Is there an easy way to do this with LINQ? The closest I have come this far is to take more than the maximum number and work with it:

 IEnumerable<Contact> Search(string name) { // validation/cleanup on name parameter var matching = _repository.Search(name); var toReturn = matching.Take(26).ToList(); if (toReturn.Count() > 25) { throw new Exception("Too many results"); } return toReturn; } 

However, this seems a little clunkier than necessary.

+4
source share
2 answers

Your method is the best method. I have not made any changes at all.

Any other option, for example, first asks for a counter, does what seems like an expensive operation (doing an actual search) twice if you have less than 26 items. You save only a small bit in case of an error and add significant overhead to the general case.

The only time your code is less desirable is if _repository.Search(name) returns a type that can be cheaply repeated twice and this can cheaply provide it with an account (e.g. List ), but in a context that doesn't seem to be the case .

+9
source

You can create your own iterator block extension method and use it for any IEnumerable<T> :

 public static class EnumerableExtensions { public static IEnumerable<T> TakeWithMaximum<T>(this IEnumerable<T> source, int maxCount) { if (source == null) throw new ArgumentNullException("source"); int count = 0; foreach (T item in source) { if (++count > maxCount) throw new InvalidOperationException(string.Format("More than the maximum specified number of elements ({0}) were returned.", maxCount)); yield return item; } } } 
0
source

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


All Articles