csharp LINQ&Lambda表达式(基本).cs

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp LINQ&Lambda表达式(基本).cs相关的知识,希望对你有一定的参考价值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LINQ
{
	class Book
    {
        public string Title { get; set; }
        public double Price { get; set; }
    }
	
	 class Account
    {
        public string Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public double Balance { get; set; }
    }
	
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("\n==========================PART 1===============================");
            List<Book> bookList = new List<Book>()
            {
                new Book() {Title = "C for Contest", Price = 200},
                new Book() {Title = "Java How to Program", Price = 500},
                new Book() {Title = "C# How to Program", Price = 700}
            };

            //using LINQ
            var selectedBooks1 = from book in bookList
                                 where book.Price >= 500
                                 select book;

            //u can use Lambda Expression also (same result)
            var selectedBooks2 = bookList.Where(book => book.Price >= 500);

            //First select books with title containing 'P' and later select all the string titles collection from those books and setting to a list
            //IEnumerable interface has been implemented in List<T> generic type, so List<T> has HAS-A relationship with IEnumerable
            IEnumerable<string> selectedBooksTitle = (bookList.Where(book => book.Title.Contains("P"))).Select(title => title.Title);
            //IEnumerable<string> selectedBooksTitle = (bookList.Where(book => book.Title.Contains("P"))).Select(book => book.Title); //works same, here this code is much readable, as we are selecting booksList with title 'P' and then from that list of books we are selecting titles of them
            Console.WriteLine("selectedBooksTitle:");
            foreach (string title in selectedBooksTitle)
            {
                Console.WriteLine(title);
            }

            Console.WriteLine("\nselectedBooks1 (LINQ):");
            foreach (Book book in selectedBooks1)
            {
                Console.WriteLine(book.Title);
            }

            Console.WriteLine("\nselectedBooks2 (LambdaExpression):");
            foreach (Book book in selectedBooks2)
            {
                Console.WriteLine(book.Title);
            }

            M1();


            Console.WriteLine("\n==========================PART 2===============================");
            List<int> numebrs = new List<int>() {1,3,5,7,10,15,20,25,30,35,40,45,50,70,90,100};
            
            //var query = numebrs;
            //var query = numebrs.Where(num => (num >= 20 && num <= 50)).ToList(); //Immediate execution
            //var query = numebrs.Where(num => (num >= 20 && num<=50)); //Deferred execution

            //var query = numebrs;
            //int inputNumberMin = 10;
            //int inputNumberMax = 30;
            //if (inputNumberMin >= 10)
            //{
            //    query = query.Where(n => n >= inputNumberMin && n <= inputNumberMax).ToList();
            //}

            //foreach (int i in query)
            //{
            //    Console.Write(i+" ");
            //}

            //ORDER BY CLAUSE
            //var query = numebrs.Where(n => n > 20).OrderByDescending(n => n);
            //foreach (int i in query)
            //{
            //    Console.Write(i + " ");
            //}

            Account[] accounts = {
                new Account() {Id = "AC001", FirstName = "Abul", LastName = "Hasan", Balance = 1000},
                new Account() {Id = "AC002", FirstName = "Kabul", LastName = "Pasan", Balance = 1500},
                new Account() {Id = "AC003", FirstName = "Habul", LastName = "Rasan", Balance = 2000},
                new Account() {Id = "AC004", FirstName = "Dabul", LastName = "Dasan", Balance = 2500},
                new Account() {Id = "AC005", FirstName = "Kuddus", LastName = "Nasan", Balance = 3000},
                new Account() {Id = "AC006", FirstName = "Mofiz", LastName = "Rasan", Balance = 3500},
                new Account() {Id = "AC007", FirstName = "Moksed", LastName = "Easan", Balance = 4000},
            };

            //var accInfo = from acc in accounts
            //              where acc.Balance >= 2000
            //              where acc.Balance <= 3000
            //              orderby acc.FirstName, acc.LastName, acc.Balance
            //              select acc;

            //var accInfo = accounts.Where(acc => acc.Balance >= 2000 && acc.Balance <= 3000)
            //            .OrderBy(acc=>acc.FirstName)
            //            .ThenBy(acc=>acc.LastName)
            //            .ThenBy(acc=>acc.Balance);

            //foreach (var acc in accInfo)
            //{
            //    Console.WriteLine(acc.FirstName + " " + acc.LastName + " " + acc.Balance);
            //}


            //SELECT A PARTICULAR PROJECTION AREA (This will return a list of double balances, not list of accounts)
            //var accInfo = accounts.Where(acc => acc.Balance >= 2000 && acc.Balance <= 3000)
            //    .OrderBy(acc => acc.FirstName)
            //    .ThenBy(acc => acc.LastName)
            //    .ThenBy(acc => acc.Balance)
            //    .Select(acc => acc.Balance); //SELECTING double Balance only (so accInfo is a list of double)

            //foreach (var acc in accInfo)
            //{
            //    Console.WriteLine(acc); //Here acc is an Balance (cause we have selected Balance from account list
            //}


            //Return multiple collumn by PROJECTION FILTERING (like acc.FirstName and acc.Balance) data from such a projection : - u have to use annonymous type
            var accInfo = accounts.Where(acc => acc.Balance >= 2000 && acc.Balance <= 3000)
                .OrderBy(acc => acc.FirstName)
                .ThenBy(acc => acc.LastName)
                .ThenBy(acc => acc.Balance)
                .Select(acc => new {fName=acc.FirstName, lName=acc.LastName, Bal=acc.Balance});  //called FLAT SEQUENCES if properties of multiple object is attached to a single collection accInfo


            foreach (var anAcc in accInfo)
            {
                Console.WriteLine(anAcc.fName+" "+anAcc.lName+" "+anAcc.Bal);
            }

            Console.ReadKey();
        }

        public static void M1()
        {
            var books = new[] {
                        new {Title = "Prejudice", Price = 1300},
                        new {Title = "Justice", Price = 3000},
                        new {Title = "War & Peace", Price = 1700},
                        new {Title = "Computer Programming", Price = 700}
                      };
            var selectedBooks = from book in books
                                where book.Price > 1000
                                select book;

            Console.WriteLine("\nLINQ using var:");
            foreach (var aBook in selectedBooks)
            {
                Console.WriteLine(aBook.Title);
            }
        }
    }
}

以上是关于csharp LINQ&Lambda表达式(基本).cs的主要内容,如果未能解决你的问题,请参考以下文章

LINQ:使用 Lambda 表达式获取 CheckBoxList 的所有选定值

Lambda vs LINQ-“表达式总是错误的”

Linq Where() lambda 表达式中的“或”等价物

Linq之Lambda表达式

如何为 sql 编写 lambda (linq) 表达式?

点标记(lambda表达式+linq查询标记符)与linq语句(查询表达式)