高效的LINQ语句(二)

Program.cs代码如下:

 class Program
    {
        private static void Main(string[] args)
        {
            //Sum_All_Scores_Remove_Three_Lowest();
            //Grouping();
            //Group_By_Age_From_Birthdate();
            Title_Of_Longest_Book();
            Console.ReadKey();
        }

         
        public static void Sum_All_Scores_Remove_Three_Lowest()
        {
            var scores = "10,5,0,8,10,1,4,0,10,1";
            var desiredScoreSum = scores
                .Split(',')
                .Select(s => int.Parse(s))
                .OrderBy(s => s)
                .Skip(3)
                .Sum();
            Console.WriteLine(desiredScoreSum);
        }

        public static void Grouping()
        {
            var orders = new List<Order>()
            {
                new Order {Id = 123, Amount = 29.95m, CustomerId = "Mark", Status = "Delivered"},
                new Order {Id = 456, Amount = 45.00m, CustomerId = "Steph", Status = "Refunded"},
                new Order {Id = 768, Amount = 32.50m, CustomerId = "Claire", Status = "Delivered"},
                new Order {Id = 222, Amount = 300.00m, CustomerId = "Mark", Status = "Delivered"},
                new Order {Id = 333, Amount = 465.00m, CustomerId = "Steph", Status = "Awaiting Stock"},
                new Order {Id = 333, Amount = 465.00m, CustomerId = "Steph", Status = "Awaiting Stock"},
            };

            Dictionary<string, List<Order>> ordersByCustomer = OrdersByCustomer(orders);
            foreach (var kvp in ordersByCustomer)
            {
                Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value.Count);
            }

            //
            Dictionary<string, List<Order>> ordersByCustomer2 = orders.GroupBy(o => o.CustomerId).ToDictionary(g => g.Key, g => g.ToList());
            foreach (var kvp in ordersByCustomer2)
            {
                Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value.Count);
            }

        }
        private static Dictionary<string, List<Order>> OrdersByCustomer(List<Order> orders)
        {
            var dict = new Dictionary<string, List<Order>>();
            foreach (var order in orders)
            {
                if (!dict.ContainsKey(order.CustomerId))
                {
                    dict[order.CustomerId] = new List<Order>();
                }
                dict[order.CustomerId].Add(order);
            }
            return dict;
        }

        public static void Group_By_Age_From_Birthdate()
        {
            string namesAndAges = "Phillip Do, 10/10/1978; Mony Taing, 11/10/1979; Mason Do, 03/23/2009; Emma Do, 11/09/2010";
            var result = namesAndAges
                .Split(';')
                .Select(n => n.Split(','))
                .Select(
                    n =>
                        new
                        {
                            Name = n[0].Trim(),
                            DateOfBirth = DateTime.ParseExact(n[1].Trim(), "M/d/yyyy", CultureInfo.InvariantCulture)
                        })
                .OrderByDescending(n => n.DateOfBirth)
                .Select(n =>
                {
                    DateTime today = DateTime.Today;
                    int age = today.Year - n.DateOfBirth.Year;
                    if (n.DateOfBirth > today.AddYears(-age))
                    {
                        age--;
                    }
                    return new { Name = n.Name, Age = age };
                });

            foreach (var item in result)
	        {
                Console.WriteLine(item.Name + "----" + item.Age);
	        }
           
        }

        //---------------------------------------------------------------------------------------------------
        public static void Group_By_Age_From_Birthdate_Clean()
        {
            Func<string, DateTime> parseDob =
                dob => DateTime.ParseExact(dob.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
            Func<DateTime, int> getAge = dateOfBirth =>
            {
                DateTime today = DateTime.Today;
                int age = today.Year - dateOfBirth.Year;
                if (dateOfBirth > today.AddYears(-age)) age--;
                return age;
            };

            string namesAndAges =
                "Phillip Do, 10/10/1978; Mony Taing, 11/10/1979; Mason Do, 03/23/2009; Emma Do, 11/09/2010";
            var result = namesAndAges
                .Split(';')
                .Select(n => n.Split(','))
                .Select(n => new { Name = n[0].Trim(), DateOfBirth = parseDob(n[1].Trim()) })
                .OrderByDescending(n => n.DateOfBirth)
                .Select(n => new { Name = n.Name, Age = getAge(n.DateOfBirth) });
        }

        private DateTime ParseDob(string dob)
        {
            return DateTime.ParseExact(dob.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
        }

        private int GetAge(DateTime dateOfBirth)
        {
            DateTime today = DateTime.Today;
            int age = today.Year - dateOfBirth.Year;
            if (dateOfBirth > today.AddYears(-age))
            {
                age--;
            }
            return age;
        }
        //---------------------------------------------------------------------------------------------------
        public static void Title_Of_Longest_Book()
        {
            var books = new[]
            {
                new {Author = "Robert Martin", Title = "Clean Code", Pages = 464},
                new {Author = "Oliver Sturm", Title = "Functional Programming in C#", Pages = 270},
                new {Author = "Martin Fowler", Title = "Patterns of Enterprise Application Architecture", Pages = 533},
                new {Author = "Bill Wagner", Title = "Effective C#", Pages = 328}
            };

            var mostPages = books.Max(x => x.Pages);
            var result1 = books.First(b => b.Pages == mostPages);
            var result2 = books.OrderByDescending(b => b.Pages).First();

            // 最好性能
            var result3 = books.Aggregate((agg, next) => next.Pages > agg.Pages ? next : agg);
            Console.WriteLine(result3.Title);
        }
    
    
    }

Model层:

 public class Entities
    {
        public string Name { get; set; }
        public List<string> Pets { get; set; }
    }

    public class Order
    {
        public int Id { get; set; }
        public decimal Amount { get; set; }
        public string CustomerId { get; set; }
        public string Status { get; set; }
    }



你可能感兴趣的:(.net,C#,LINQ,高级,高效)