static void Linq()
        {
            var books = new BookRepository().GetBooks();

            //Query Operators
            //find books cheaper than $10 sorted by title, project to title
            var cheaperBooks = from b in books
                               where b.Price < 10
                               orderby b.Title
                               select b.Title;

            //Extension Methods
            //same as above
            var cheapBooks = books
                             .Where(b => b.Price < 10)
                             .OrderBy(b => b.Title)
                             .Select(b => b.Title);

            //skip the first two objects, and return the next three
            var pagedBooks = books.Skip(2).Take(3);

            //min-max-average-sum returns
            var maxPrice     = books.Max(b => b.Price);
            var minPrice     = books.Min(b => b.Price);
            var totalPrices  = books.Sum(b => b.Price);
            var averagePrice = books.Average(b => b.Price);

            Console.WriteLine(averagePrice);
        }
示例#2
0
        public void LinqWhereExample()
        {
            var books = new BookRepository().GetBooks();

            //Linq query Operators
            var cheapBooks = from b in books
                             where b.Price < 20
                             orderby b.Title
                             select b;

            //Linq Extension methods
            var cheapBooks1 = books
                              .Where(b => b.Price < 10)
                              .OrderBy(b => b.Title)
                              .Select(b => b.Title);

            //select single object
            //single means atleast one object else it will throw error
            var checkbooks = books.SingleOrDefault(b => b.Title == "Asp.net MVC");

            //first object in the collection
            var book = books.First(b => b.Title == "C# Advanced Topics");

            var book1 = books.FirstOrDefault(b => b.Title == "C# Advanced Topics");

            //skip using paging records Skip(2) means skip 2 records and take the remain no
            var bookSkip = books.Skip(2).Take(3); //used for pagination

            // count
            int rcCount = books.Count();

            var maxPrice   = books.Max(b => b.Price);
            var minPrice   = books.Min(b => b.Price);
            var totalPrice = books.Sum(b => b.Price); //sumbasedonpriceofbook
            var avg        = books.Average(b => b.Price);
        }