class Program
{
static void Main(string[] args)
{
{
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; }
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;
}
}
public Person(int _id,decimal _price)
{
Id = _id;
Price = _price;
}
}