C# List的並集、交集、差集


並集---Union

集合的並集是 合並兩個集合的所有項,去重,如下圖所示:

 

 

 
  1. List<int> ls1 = new List<int>() { 1,2,3,5,7,9 };
  2. List<int> ls2 = new List<int>() { 2,4,6,8,9,10};
  3. IEnumerable<int> unionLs = ls1.Union(ls2);
  4. foreach (int item in unionLs)
  5. {
  6. Console.Write("{0}\t", item);
  7. }

 

交集---Intersect

集合的交集是 取集合的共同的項,如下圖所示:

 

 

 
  1. List<int> ls1 = new List<int>() { 1,2,3,5,7,9 };
  2. List<int> ls2 = new List<int>() { 2,4,6,8,9,10};
  3. IEnumerable<int> intersectLs = ls1.Intersect(ls2);
  4. foreach (int item in intersectLs)
  5. {
  6. Console.Write("{0}\t",item);
  7. }

 

差集---Except

集合的差集是 取在該集合中而不在另一集合中的所有的項,如下圖所示:

 

 


 

 

List<int> ls1 = new List<int>() { 1,2,3,5,7,9 };
List<int> ls2 = new List<int>() { 2,4,6,8,9,10};
 
 
IEnumerable<int> exceptLs = ls1.Except(ls2);
foreach (int item in exceptLs)
{
Console.Write("{0}\t", item);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM