List中常用的linq操作

 

复制代码
 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)

posted @   YorkShare  阅读(915)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示