分享一些高效的LINQ語句代碼

來源:互聯網
上載者:User

Model層的類如下:

public class Order    {        public int Id { get; set; }        public decimal Amount { get; set; }        public string CustomerName { get; set; }        public string Status { get; set; }    }
public  class Person    {        public string Name { get; set; }        public int Age { get; set; }    }

Program.cs代碼如下:

 class Program    {        //AutoResetEvent 允許線程通過發訊號互相通訊。通常,此通訊涉及線程需要獨佔訪問的資源。        //線程通過調用 AutoResetEvent 上的 WaitOne 來等待訊號。如果 AutoResetEvent 處於非終止狀態,則該線程阻塞,並等待當前控制資源的線程,通過調用 Set 發出資源可用的訊號。        //調用 Set 向 AutoResetEvent 發訊號以釋放等待線程。AutoResetEvent 將保持終止狀態,直到一個正在等待的線程被釋放,然後自動返回非終止狀態。如果沒有任何線程在等待,則狀態將無限期地保持為終止狀態。        //可以通過將一個布爾值傳遞給建構函式來控制 AutoResetEvent 的初始狀態,如果初始狀態為終止狀態,則為 true;否則為 false。        //通俗的來講只有等myResetEven.Set()成功運行後,myResetEven.WaitOne()才能夠獲得運行機會;Set是發訊號,WaitOne是等待訊號,只有發了訊號,等待的才會執行。如果不發的話,WaitOne後面的程式就永遠不會執行。        private static AutoResetEvent autoSet = new AutoResetEvent(false);        private static List<Person> list = new List<Person>()        {            new Person() {Name = "Rose", Age = 19},            new Person() {Name = "Steve", Age = 45},            new Person() {Name = "Jessica", Age = 20},        };        private static void Main(string[] args)        {            //CheckOrders();            //Common();            //RemoveFromList();            //ExceptionHandling();            //-----------------------------------------------------------------            //--------------------------------類比非安全執行緒----------------------------            Thread t1 = new Thread(() =>            {                //確保等待t2開始之後才運行下面的代碼                autoSet.WaitOne();                foreach (var item in list)                {                    Console.WriteLine("t1:" + item.Name);                    Thread.Sleep(1000);                }            });            t1.Start();            Thread t2 = new Thread(() =>            {                //通知t1可以執行代碼                autoSet.Set();                //沉睡1秒是為了確保刪除操作在t1的迭代過程中                Thread.Sleep(1000);                list.RemoveAt(2);            });            t2.Start();            Console.ReadKey();        }        public static void CheckOrders()        {            List<Order> orders = new List<Order>()            {                new Order { Id = 123, Amount = 29.95m, CustomerName = "Mark", Status = "Delivered" },                new Order { Id = 456, Amount = 45.00m, CustomerName = "Steph", Status = "Refunded" },                new Order { Id = 768, Amount = 32.50m, CustomerName = "Claire", Status = "Delivered" },            };            bool anyRefunded = orders.Any(o => o.Status == "Refunded");            if (anyRefunded)            {                Console.WriteLine("There are refunded orders");            }            else            {                Console.WriteLine("No refunds");            }            bool allDelivered = orders.All(o => o.Status == "Delivered");            if (allDelivered)            {                Console.WriteLine("Everything was delivered");            }            else            {                Console.WriteLine("Not everything was delivered");            }        }        public static void Common()        {            //距離聖誕節的天數            var daysToChristmas = (new DateTime(DateTime.Today.Year, 12, 25) - DateTime.Today).TotalDays;            Console.WriteLine(daysToChristmas);            //-----------------------------------------------------------------            int SUM = "10,5,0,8,10,1,4,0,10,1"                .Split(',')                .Select(int.Parse)                .OrderBy(n => n)                .Skip(3)                .Sum();            Console.WriteLine(SUM);            //-----------------------------------------------------------------            var customers = new[] {                new { Name = "Annie", Email = "annie@test.com" },                new { Name = "Ben", Email = "" },                new { Name = "Lily", Email = "lily@test.com" },                new { Name = "Joel", Email = "joel@test.com" },                new { Name = "Sam", Email = "" },            };            foreach (var customer in                from c in customers                where !String.IsNullOrEmpty(c.Email)                select c)            {                Console.WriteLine("Sending email to {0}", customer.Name);            }            //效果同上            foreach (var customer in customers.Where(c => !String.IsNullOrEmpty(c.Email)))            {                Console.WriteLine("Sending email to {0}", customer.Name);            }        }        public static void RemoveFromList()        {            Func<List<string>> makeList = () => Enumerable.Range(1, 10000000).Select(n => ("Item " + n + "")).ToList();            var itemsToRemove = new[] { "Item 0", "Item 1", "Item 50", "Item 1000", "Item 999999", "Item 9999999" };            var stopwatch = new Stopwatch();            var list = makeList();            stopwatch.Start();            foreach (var item in itemsToRemove)            {                list.Remove(item);            }            stopwatch.Stop();            Console.WriteLine(list.Count + "Foreach took {0}ms", stopwatch.ElapsedMilliseconds);            list = makeList();            stopwatch.Restart();            var newList = list.Except(itemsToRemove).ToList(); //效率極低            stopwatch.Stop();            Console.WriteLine(newList.Count + "Except took {0}ms", stopwatch.ElapsedMilliseconds);        }        public static void ExceptionHandling()        {            var numbers = Enumerable.Range(1, 10)                    .Select(n => 5 - n)                    .Select(n =>                    {                        try                        {                            return 10 / n;                        }                        catch (Exception e)                        {                            Console.WriteLine("Error in lambda: " + e.Message);                            return -1;                        }                    });            foreach (var n in numbers)            {                Console.WriteLine(n);            }        }    }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.