首页 > 其他 > 详细

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

时间:2019-12-02 22:53:07      阅读:111      评论:0      收藏:0      [点我收藏+]
    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;
        }
    }
 
技术分享图片

 

 

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

原文:https://www.cnblogs.com/xiaoxinstart/p/11973403.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!