Linq常用List操作總結,ForEach、分頁、交并集、去重、SelectMany等

  1 /*
  2 以下圍繞Person類實現,Person類只有Name和Age兩個屬性
  3 一.List<T>排序
  4 1.1 List<T>提供了很多排序方法,sort(),Orderby(),OrderByDescending().
  5 */
  6  
  7 lstPerson = lstPerson.OrderByDescending(x=>x.Name).ToList(); //降序
  8 lstPerson = lstPerson.OrderBy(x => x.Age).ToList();//升序
  9  
 10 //通過Name和Age升序
 11 lstPerson.Sort((x, y) =>
 12             {
 13                 if ((x.Name.CompareTo(y.Name) > 0) || ((x.Name == y.Name) && x.Age > y.Age))
 14                 {
 15                     return 1;
 16                 }
 17                 else if ((x.Name == y.Name) && (x.Age == y.Age))
 18                 {
 19                     return 0;
 20                 }
 21                 else
 22                 {
 23                     return -1;
 24                 }
 25             });
 26  
 27 /*
 28 1.2 因為最近有做datagrid里面像實現點擊任何一列的名稱就按照該名稱排序,那我們該怎么做呢?可能第一反應是想,為每一個屬性寫一個排序方法不就得了,其實這樣的話無意間增加的代碼量了,而且不通用,其實這里可以結合反射來實現.
 29 */
 30  
 31 string propertityName = "Name";
 32 lstPerson = lstPerson.OrderBy(x =>
 33             {
 34                 PropertyInfo[] proInfos = x.GetType().GetProperties();
 35                 return proInfos.Where(info => info.Name == propertityName).ToList()[0].GetValue(x);
 36             }).ToList();
 37  
 38 /*
 39 二.List<T>分頁
 40 2.1往往有時候我們會從后臺獲取很多數據,存放在List<T>,可是因為界面受限制無法完全展示,我們就會想到分頁顯示,對于分頁顯示我們基本上第一種想法肯定是通過循環設置每一頁的Size,
 41 其實linq有skip和take方法,skip表示跳過多少元素,take獲取特定個數元素. 看起來代碼簡潔多了.
 42 */
 43  
 44 public static List<Person> GetPageByLinq(List<Person> lstPerson, int pageIndex, int PageSize)
 45 {
 46     return lstPerson.Skip((pageIndex - 1) * PageSize).Take(PageSize).ToList();
 47 }
 48  
 49 /*
 50 三,List<T>之foreach用法.
 51 2.1 如何我相對List里面的每個對象執行相同操作的話,以前都是通過for循環遍歷,其實Linq提供了便捷的Foreach來實現。下面我將對所有的Person年齡+2.
 52 */
 53  
 54 lstPerson.ForEach(x => x.Age= x.Age + 2);
 55  
 56 /*兩個集合之間操作*/
 57 List<string> ListResult = new List<string>();
 58 ListResult = ListA.Distinct().ToList();//去重
 59 ListResult = ListA.Except(ListB).ToList();//差集
 60 ListResult = ListA.Union(ListB).ToList();  //并集
 61 ListResult = ListA.Intersect(ListB).ToList();//交集
 62  
 63 //這里有7個老師,每個人有3個學生,總共21一個學生里,我們想要獲得這3個未及格的學生集合。
 64 public class Student
 65 {
 66     public string StudentName { get; set; }
 67     public int Score { get; set; }
 68  
 69     public Student(string StudentName,int Score)
 70     {
 71         this.StudentName = StudentName;
 72         this.Score = Score;
 73     }
 74 }
 75 public class Teacher
 76 {
 77     public string TeacherName { get; set; }
 78     public List<Student> Students { get; set; }
 79     public Teacher(string TeacherName, List<Student> Students)
 80     {
 81         this.TeacherName = TeacherName;
 82         this.Students = Students;
 83     }
 84 }
 85  
 86 using System;
 87 using System.Collections.Generic;
 88 using System.Linq;
 89 using System.Text;
 90  
 91 namespace TestLinq
 92 {
 93     class Program
 94     {
 95         static void Main(string[] args)
 96         {
 97             //運行結果見下圖
 98             List<Teacher> teachers = new List<Teacher>
 99             {
100                 new Teacher("張老師",new List<Student>{ new Student("張三1", 100),new Student("李四1", 90),new Student("王五1", 30) }), //
101                 new Teacher("李老師",new List<Student>{ new Student("張三2", 100),new Student("李四2", 90),new Student("王五2", 60) }),
102                 new Teacher("趙老師",new List<Student>{ new Student("張三3", 100),new Student("李四3", 90),new Student("王五3", 40) }), //
103                 new Teacher("孫老師",new List<Student>{ new Student("張三4", 100),new Student("李四4", 90),new Student("王五4", 60) }),
104                 new Teacher("錢老師",new List<Student>{ new Student("張三5", 100),new Student("李四5", 90),new Student("王五5", 50) }), //
105                 new Teacher("周老師",new List<Student>{ new Student("張三6", 100),new Student("李四6", 90),new Student("王五6", 60) }),
106                 new Teacher("吳老師",new List<Student>{ new Student("張三7", 100),new Student("李四7", 90),new Student("王五7", 60) })
107             };
108  
109             #region 所有任課老師下未及格的學生 方式一
110             List<Student> studentList = new List<Student>();
111             foreach (var t in teachers)
112             {
113                 foreach (var s in t.Students)
114                 {
115                     if (s.Score < 60)
116                     {
117                         studentList.Add(s);
118                     }
119                 }
120             }
121             studentList.ForEach(s => Console.WriteLine(string.Format("{0} - {1}", s.StudentName, s.Score)));
122             #endregion
123  
124             Console.ReadKey();
125  
126             #region 所有任課老師下未及格的學生 方式二
127             var list1 = from t in teachers
128                         from s in t.Students
129                         where s.Score < 60
130                         select s;
131             foreach (var item in list1)
132             {
133                 Console.WriteLine(string.Format("{0} - {1}", item.StudentName, item.Score));
134             }
135             #endregion
136  
137             Console.ReadKey();
138  
139             #region 所有任課老師下未及格的學生 方式三
140             var list2 = teachers.SelectMany(t => t.Students).Where(s => s.Score < 60);
141  
142             foreach (var s in list2)
143             {
144                 Console.WriteLine(string.Format("{0} - {1}", s.StudentName, s.Score));
145             }
146             #endregion
147  
148             Console.ReadKey();
149  
150             #region 所有未及格的學生及其授課老師 
151             var list3 = teachers.SelectMany(
152                 t => t.Students,
153                 (t, s) => new { t.TeacherName, s.StudentName, s.Score })
154                 .Where(n => n.Score < 60);
155  
156             foreach (var item in list3)
157             {
158                 Console.WriteLine(string.Format("任課老師{0} - 學生{1} 分數{2}", item.TeacherName, item.StudentName, item.Score));
159             }
160             #endregion
161             Console.ReadKey();
162         }
163     }
164 }

?

轉載于:https://www.cnblogs.com/jasonlai2016/p/9957863.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/396057.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/396057.shtml
英文地址,請注明出處:http://en.pswp.cn/news/396057.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

bool查詢原理 es_ES系列之原理copy_to用好了這么香

寫在前面Elasticsearch(以下簡稱ES)有個copy_to的功能&#xff0c;之前在一個項目中用到&#xff0c;感覺像是發現了一個神器。這個東西并不是像有些人說的是個語法糖。它用好了不但能提高檢索的效率&#xff0c;還可以簡化查詢語句。基本用法介紹直接上示例。先看看mapping&am…

加密算法—MD5、RSA、DES

最近因為要做一個加密的功能&#xff0c;簡單了解了一下加密算法&#xff0c;現在比較常用的有三個加密算法MD5加密算法、RSA加密算法、DES加密算法。 MD5加密算法 定義&#xff1a;MD5算法是將任意長度的“字節串”變換成一個128bit的大整數&#xff0c;并且它是一個不可逆的字…

隨機加密_隨機藝術和加密圣誕樹

隨機加密When I first learned how to code, one of my first tasks was setting up an SSH key so I could use encryption to securely connect to my friend’s Linux server.當我第一次學習如何編碼時&#xff0c;我的第一個任務是設置SSH密鑰&#xff0c;以便可以使用加密…

用c語言編寫一個2048 游戲,求c語言編寫的2048游戲代碼,盡量功能完善一些

正在編寫中&#xff0c;請稍后&#xff01;追答 : 代碼來了&#xff01;有點急&#xff0c;沒做界面。追答 : 2048_launcher。c&#xff1a;#include#include#includevoid main(){printf("正在啟動中&#xff0c;請稍后&#xff01;");Sleep(1000);system("bin\…

MySQL之數據庫對象查看工具mysqlshow

mysqlshow&#xff1a;數據庫對象查看工具&#xff0c;用來快速查找存在哪些數據庫、數據庫中的表、表中的列或索引。選項&#xff1a;--count 顯示數據庫和表的統計信息-k 顯示指定的表中的索引-i 顯示表的狀態信息不帶任何參數顯示所有數據庫[rootwww mys…

軟件工程分組

電子零售系統 陳仔祥 孟拓 陳庚 汪力 郭澳林 崔祥岑 劉校 肖宇 武清 胡圣陽轉載于:https://www.cnblogs.com/2231c/p/9960751.html

vnr光學識別怎么打開_干貨|指紋鎖的指紋識別模塊的前世今生,智能鎖的指紋識別到底有多智能?...

智能鎖現在也有很多叫法&#xff1a;指紋鎖、電子鎖。可見指紋識別是智能鎖的核心功能了&#xff0c;那我們今天來聊聊智能鎖的指紋識別模塊。指紋識別的歷史指紋識別認證的流程指紋識別技術的種類指紋識別的歷史早在2000多年前我國古代的人就將指紋用于簽訂合同和破案了&#…

使用Kakapo.js進行動態模擬

by zzarcon由zzarcon 使用Kakapo.js進行動態模擬 (Dynamic mocking with Kakapo.js) 3 months after the first commit, Kakapo.js reaches the first release and we are proud to announce that now it is ready to use. Let us introduce you Kakapo.首次提交3個月后&#…

android ble 實現自動連接,Android:自動重新連接BLE設備

經過多次試驗和磨難之后,這就是我最好讓Android自動連接的唯一用戶操作是首先選擇設備(如果使用設置菜單然后首先配對).您必須將配對事件捕獲到BroadcastReceiver中并執行BluetoothDevice.connectGatt()將autoconnect設置為true.然后當設備斷開連接時,調用gatt.connect().更新&…

萊斯 (less)

less中的變量 1、聲明變量&#xff1a;變量名&#xff1a;變量值 使用變量名&#xff1a;變量名 less中的變量類型 ①數字類1 10px ②字符串&#xff1a;無引號字符串red和有引號字符串"haha" ③顏色類red#000000 rgb() …

hackintosh黑蘋果_如何構建用于編碼的Hackintosh

hackintosh黑蘋果by Simon Waters西蒙沃特斯(Simon Waters) 如何構建用于編碼的Hackintosh (How to build a Hackintosh for coding) Let’s talk about Hackintosh-ing — the installation of Mac OS X on PC hardware.我們來談談Hackintosh-ing-在PC硬件上安裝Mac OSX。 I…

hide show vue 動畫_(Vue動效)7.Vue中動畫封裝

關鍵詞&#xff1a;動畫封裝——進行可復用一、如何封裝&#xff1f;1、使用&#xff1a;局部組件傳遞數據局部組件中使用JS動畫2、原理&#xff1a;將動畫效果完全第封裝在一個名為<fade>的組件中&#xff0c;今后如要復用&#xff0c;只需要復制有其組件名的部分&#…

android項目編譯命令行,命令行編譯Android項目

1. 生成R文件> aapt package -f -m -J ./gen -S res -M AndroidManifest.xml -I D:\android.jar-f 如果編譯生成的文件已經存在&#xff0c;強制覆蓋。-m 使生成的包的目錄存放在-J參數指定的目錄-J 指定生成的R.java 的輸出目錄路徑-S 指定res文件夾的路徑-I 指定某個版本平…

jQuery datepicker和jQuery validator 共用時bug

當我們給一個元素綁定一個datepick后又要對它用validator進行驗證時會發現驗證并沒有成功 因為當點擊該元素時候input彈出datepick的UI就已經失去了焦點它驗證的仍然是前一個值&#xff0c; 不過還好 datepick提供了onSelect 事件我們可以在這個事件觸發的時候重新把焦點在賦給…

《Python地理數據處理》——導讀

前言本書可以幫助你學習使用地理空間數據的基礎知識&#xff0c;主要是使用GDAL / OGR。當然&#xff0c;還有其他選擇&#xff0c;但其中一些都是建立在GDAL的基礎之上&#xff0c;所以如果你理解了本書中的內容&#xff0c;就可以很輕松地學習其他知識。這不是一本關于地理信…

記一次Java AES 加解密 對應C# AES加解密 的一波三折

最近在跟三方對接 對方采用AES加解密 作為一個資深neter Ctrl CV 是我最大的優點 所以我義正言辭的問他們要了demo java demo代碼&#xff1a; public class EncryptDecryptTool {private static final String defaultCharset "UTF-8";private static final String …

zemax評價函數編輯器_ZEMAX與光學設計案例:激光擴束系統詳細設計與公差分析(二)...

目前超過兩千人的光學與光學設計方面的微信公眾號&#xff0c;歡迎您的到來&#xff01;激光擴束系統公差分析ZEMAX與光學設計案例&#xff1a;激光擴束系統詳細設計與公差分析(二)作者&#xff1a;墨子川上10倍擴束系統在上篇已經設計好了&#xff0c;接下來就是進行系統的公差…

決策者根據什么曲線做出決策_如何做出產品設計決策

決策者根據什么曲線做出決策by Tanner Christensen由Tanner Christensen 如何做出產品設計決策 (How Product Design Decisions are Made) Recently in a Facebook group dedicated to designers, known as Designers Guild, a young design student named Marina Candela ask…

移動前端框架重構幾個關鍵問題

1. 是否該廢棄iscroll&#xff1f; 我得出的結論是&#xff0c;是該廢棄了。那當時為什么要用iscroll&#xff1f; 原因有三個&#xff1a; 1. 因為別人也用了。 2. 為了iPhone上頁面滑動更順暢。 3. 為了用上拉、下拉刷新。 關于這三個原因有幾點觀點&#xff1a; 1. 人最容易…

android 內部共享存儲,Android共享內部存儲

我現在面對txt文件的類似情況,并做到了這一點.File downloadedFile new File( context.getFilesDir(),"simple.txt" );downloadedFile.setReadable( true,false );downloadedFile.setWritable( true,false ); //set read/write for othersUri downloadFileUri Uri.f…