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) {
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.
source share