asp.net 获得数组里面的交集,并集等
功能: 主要是取得2個Collection 裏,相同、相異、聯集的部份
必需加入的dll: Iesi.Collections.dll
範例:
using System; | |
2 | using Iesi.Collections.Generic; |
3 | |
4 | public partial class TestPage_SetDemoPage : System.Web.UI.Page { |
5 | protected void Page_Load(object sender, EventArgs e) { |
6 | ISet<string> Girls = new HashedSet<string>(); |
7 | Girls.Add("Christine"); |
8 | Girls.Add("Eva"); |
9 | Girls.Add("Jean"); |
10 | Girls.Add("Novia"); |
11 | Girls.Add("Winnie"); |
12 | |
13 | ISet<string> PMs = new HashedSet<string>(); |
14 | PMs.Add("Eva"); |
15 | PMs.Add("Novia"); |
16 | PMs.Add("Vincent"); |
17 | PMs.Add("Williams"); |
18 | PMs.Add("Winnie"); |
19 | |
20 | ISet<string> GirlPMs = Girls.Intersect(PMs); |
21 | Response.Write("是女生且是PM: <br />"); |
22 | foreach (string s in GirlPMs) { |
23 | Response.Write(s + "<br />"); |
24 | } |
25 | |
26 | Response.Write("<br />"); |
27 | ISet<string> GirlNotPMs = Girls.Minus(PMs); |
28 | Response.Write("是女生且不是PM: <br />"); |
29 | foreach (string s in GirlNotPMs) { |
30 | Response.Write(s + "<br />"); |
31 | } |
32 | |
33 | Response.Write("<br />"); |
34 | ISet<string> GirlOrPMs = Girls.Union(PMs); |
35 | Response.Write("是女生或是PM: <br />"); |
36 | foreach (string s in GirlOrPMs) { |
37 | Response.Write(s + "<br />"); |
38 | } |
39 | |
40 | Response.Write("<br />"); |
41 | ISet<string> NotMatch = Girls.ExclusiveOr(PMs); |
42 | Response.Write("是女生但不是PM,或是PM但不是女生: <br />"); |
43 | foreach (string s in NotMatch) { |
44 | Response.Write(s + "<br />"); |
45 | } |
46 | } |
47 | } |
補充:(该方法支持.net2.0)
1. 如果順序是重要的,那 HashedSet 可以改成 SortedSet
2. 如果用SortedSet, 集合內的物件必需繼承IComparable介面
3. 更詳盡的介紹可參考 Add Support for "Set" Collections to .NET
4.Iesi.Collection.dll 可在 NHibernate 專案裏找到, 裏面的版本加上對泛型的支援
net3.0以上版本直接使用linq就可以了
- C# code
-
var Girls = new[] {"Christine", "Eva", "Jean", "Novia", "Winnie"}; var PMs = new[] {"Eva", "Novia", "Vincent", "Williams", "Winnie"}; // 是 Girl 且是 PM (交集) foreach (var s in Girls.Intersect(PMs)) { Console.WriteLine(s } Console.WriteLine();
posted on 2010-07-27 16:22 Bright Leopold 阅读(743) 评论(0) 编辑 收藏 举报