欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

分享一些高效的LINQ语句代码

程序员文章站 2022-03-22 13:54:40
...

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);
            }
        }

    }

以上就是分享一些高效的LINQ语句代码的详细内容,更多请关注其它相关文章!