• GroupBy之后加ToList和不加ToList有什么区别吗?


        class Program
        {
            static void Main(string[] args)
            {
                List<Person> people = new List<Person>() {
                    new Person(1,12),
                     new Person(1,24),
                      new Person(1,26)
                };
                var pers = people.GroupBy(p => p.Id)
                    .Select(p => new Person()
                    {
                        Id = p.Key,
                        Price = p.Sum(a => a.Price)
                    }).ToList();//ToList了后面people 里面再加新的元素不会影响 到pers的值,已经指向了新的地址
                var pers1 = people.GroupBy(p => p.Id)
                 .Select(p => new Person()
                 {
                     Id = p.Key,
                     Price = p.Sum(a => a.Price)
                 });//people加新的元素之后,pers1的值会随之改变,因为指向的是同一地址
                people.Add(new Person(1,20));
                Console.WriteLine("加了ToList之后的pers的总和为{0}",pers.FirstOrDefault().Price);
                Console.WriteLine("没加ToList的pers1的总和为{0}", pers1.FirstOrDefault().Price);
            }
          
        }
        public class Person
        {
            private int _id;
            private decimal _price;
            public int Id { get; set; }
            public decimal Price { get; set; }
            public Person()
            {
            }
            public Person(int _id,decimal _price)
            {
                Id = _id;
                Price = _price;
            }
        }
     
  • 相关阅读:
    数据库系列之查询(4)
    数据库系列之查询(3)
    数据库系列之查询(2)
    数据库系列之查询(1)
    数据库系列之视图
    数据库系列之数据管理(删除数据)
    数据库系列之数据管理(更新数据)
    数据库系列之数据管理(插入数据)
    数据库管理之数据表管理(2)
    数据库管理之数据表管理(1)
  • 原文地址:https://www.cnblogs.com/xiaoxinstart/p/11973403.html
Copyright © 2020-2023  润新知