list1.Add( 1);
list1.Add( 2);
list1.Add( 3);
List< int> list2 = new List< int>();
list2.Add( 3);
list2.Add( 4);
list2.Add( 5);
// 得到的結果是4,5 即減去了相同的元素。
List< int> list3 = list2.Except(list1).ToList();
foreach ( int i in list3)
{
MessageBox.Show(i.ToString());
}
List< int> numbers2 = new List< int>() { 15, 14, 11, 13, 19, 18, 16, 17, 12, 10 };
var newQuerty = numbers1.Concat(
from n in numbers2
where !numbers1.Contains(n)
select n
).OrderBy(n=>n);
int[] A={1,2,2,3,4,5,6,6,6};
int[] B={2,2,2,3,7,8,9,5};
List<int> list = new List<int>(A);
list.AddRange(B);
list.Sort();
//去除重復項
foreach (int i in list.Distinct<int>())
{
Console.WriteLine(i);
}
以往我們都是肯定絞盡腦汁,肯定什么循環,元素大小,什么因素都考慮進去。但是現在采用Linq可以很好的解決這個問題。找出兩個或多個數組的相同項。 代碼相當簡單: usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespaceTest4_03 { classProgram { staticvoidMain(string[] args) { string[] names = {"Adams","Arthur","Buchanan","Tsbuchis","ShCian","FuchsiaLinda","DecheChen","Lotheer","FindLanciCade","SorchLand","JiangZheng","MisiiLoda","Gtod","Dfac","Lama","BakCades","Losangle","ZheWQ","GehengDahaLothi","ToryLandey","DakaLothy","BthLanda","MenNorth","Fith","FoxMain","DontM","Saobba","Del","Sala","Ghero","BhthLaPhda"}; IEnumerable<string> skip = names.Skip(10); IEnumerable<string> take = names.Take(11); //取出兩個序列中交集部分,按理論應該輸出JiangZheng IEnumerable<string> intersect = skip.Intersect(take); foreach(varsinintersect) { Console.WriteLine(s); } Console.ReadKey(); } } } |
今天在做一個樹形選擇節點時,遇到一個問題,屬性節點是記錄了相關的ID值,第一次呢全部對這些ID進行處理,但是接下來再次選擇就要分情況了,原先選擇的ID如果不在新選擇的集合中那么剔除掉,否則,原先ID不傳入函數處理,新ID傳入函數處理: 比如原來①選擇的ID是:1,2,3,4 下次:1,2,3,4,5, 那么這時候5要處理,1,2,3,4維持原樣。 ②選擇ID是:1,3 下次: 3,4,5 那么這時候4,5 要處理,3 維持原樣。1剔除。 ③選擇ID是:1,2,3,4,5 下次:3,4,5 那么這時候3,4,5都維持原樣,1,2剔除。 ④選擇ID是:1,2 下次:3,4,5 那么這時候3,4,5處理,1,2剔除。
簡化一下數學模型: 大家發現沒其實這就是一個數學的概念,集合的差集,那么我們怎么處理呢? 假設前次選擇的集合為A,后次選擇為B 得到要處理的很簡單:B-A (B與A的差集)就是要處理的集合元素,為什么呢?根據概念可知哈! 那么得到不做處理的怎么辦呢? 不要處理的必然是B的子集,那么怎么得到呢? 出來啦既是:B-(B-A) 這是為什么呢? B-A 就是要處理的,而維持原樣的就是當然就是:B-(B-A), 那么剔除的集合呢? A-(B-(B-A))
如何用C#表示呢,我這里就不用什么循環之類的了,我用的是NET3.5 那就好辦了,用Linq處理: 俺這里特殊點,右鍵得到的樹形集合(lstSource)包含了其他信息,先獲取ID集合再說: var m_ilAllSelect = lstSource.Select(r => r.ID).AsEnumerable();//新選擇的列表 ///////下面開始處理了 List<int> m_ilNewSelect = m_ilAllSelect.ToList();//新選擇列表
為了簡化給大家,這里的A代表舊集合,B代表新集合,這里的集合都是List<int>泛型列表。 那么要處理的就是 B.Except(A), 維持原樣的:B( B.Except(A)), 剔除的:A.Except(B( B.Except(A))), 不要問我這個Except方法啥意思?看MSDN吧,google也行啦! 當然我實際的源碼比這更細致點,至此解決集合的差集的知識點就這些了! |