Esempio n. 1
0
        static void Main(string[] args)
        {
            var searchParameters = new BirdSearch
            {
                Size    = "Medium",
                Country = "United States",
                Colors  = new List <string> {
                    "White", "Brown", "Black"
                },
                Page     = 0,
                PageSize = 5
            };

            Console.WriteLine("Type any key to begin search");
            var birds = BirdRepository.LoadBirds();

            while (Console.ReadKey().KeyChar != 'q')
            {
                Console.WriteLine($"Page: {searchParameters.Page}");

                birds.Search(searchParameters).ToList().ForEach(b =>
                {
                    Console.WriteLine($"Common Name: {b.CommonName}");
                });
                searchParameters.Page++;
            }
        }
 public static IEnumerable <Bird> Search(this IEnumerable <Bird> source, BirdSearch search)
 {
     return(source.Where(s => search.CommonName == null || s.CommonName.Contains(search.CommonName))
            .Where(s => search.Country == null || s.Habitats.Any(h => h.Country.Contains(search.Country)))
            .Where(s => search.Size == null || s.Size == search.Size)
            .Where(s => search.Colors.Any(c => c == s.PrimaryColor) ||
                   search.Colors.Any(c => c == s.SecondaryColor) ||
                   search.Colors.Join(s.TertiaryColors,
                                      sc => sc,
                                      tc => tc,
                                      (sc, tc) => (sc)).Any())
            .Skip(search.Page * search.PageSize)
            .Take(search.PageSize));
 }
 public static IEnumerable <Bird> Search(this IEnumerable <Bird> source, BirdSearch search)
 {
     return(source.Where(s => search.CommonName == null || s.CommonName.Contains(search.CommonName))
            .Where(s => search.Country == null || s.Habitats.Any(h => h.Country.Contains(search.Country)))
            .Where(s => search.Size == null || s.Size == search.Size)
            .Where(s => search.Colors.Any(c => c == s.PrimaryColor) ||
                   search.Colors.Any(c => c == s.SecondaryColor) ||
                   search.Colors.Join(s.TertiaryColors,
                                      sc => cs,
                                      tc => tc,
                                      (sc, tc) => (sc)).Any())
            // now all of our colors are in our filter
            // now to deal with the Page and PageSize parameters using Skip and Take.
            .Skip(search.Page * search.PageSize)       // will skip ahead as many elements as returned to make sure nothing is missed for the user
            .Take(search.PageSize));
     // now that's all of our search logic in one LINQ expression
     // just ignore all the errors, i guess...
 }