1 [Serializable] 2 public class Product 3 { 4 public Product() 5 { 6 7 8 } 9 10 public Product(string id,string pname,int num,double price) 11 { 12 this.ProductID = id; 13 this.ProductName = pname; 14 this.Num = num; 15 this.Price = price; 16 } 17 public string ProductID { get; set; } 18 public string ProductName { get; set; } 19 public int Num { get; set; } 20 public double Price { get; set; } 21 22 23 }
初始化
1 List<Product> plist = new List<Product>() 2 { 3 new Product{ ProductID="01",ProductName ="牛奶",Num=45,Price=4.0 }, 4 new Product{ ProductID="02",ProductName ="饼干",Num=8,Price=8.5 }, 5 new Product{ ProductID="03",ProductName ="糖果",Num=9,Price=2.1 }, 6 new Product{ ProductID="04",ProductName ="饮料",Num=10,Price=3.5 }, 7 };
1.使用linq获取list集合中的某个字段值的集合
double[] Prices = plist.Select(u => u.Price).ToArray();
2.使用linq求list集合中所有对象price字段的和
var Price_sum = plist.Sum(u => u.Price)
求数量*单价的和
var Price_sum = plist.Sum(u => u.Price*u.Num)