实现IEnumerable<T>伴随一个迭代:

  1. public class MyGenCollection : IEnumerable<int>
  2. {
  3. int[] data = {1, 2, 3};
  4.  
  5. public IEnumerator<int> GetEnumerator()
  6. {
  7. foreach (int i in data)
  8. yield return i;
  9. }
  10.  
  11. IEnumerator IEnumerable.GetEnumerator() // Explicit implementation
  12. { // keeps it hidden.
  13. return GetEnumerator();
  14. }
  15. }

直接实现IEnumerable<T>:

  1. class MyIntList : IEnumerable<int>
  2. {
  3. int[] data = { 1, 2, 3 };
  4.  
  5. // The generic enumerator is compatible with both IEnumerable and
  6. // IEnumerable<T>. We implement the nongeneric GetEnumerator method
  7. // explicitly to avoid a naming conflict.
  8.  
  9. public IEnumerator<int> GetEnumerator() { return new Enumerator(this); }
  10. IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this); }
  11.  
  12. class Enumerator : IEnumerator<int>
  13. {
  14. int currentIndex = -1;
  15. MyIntList collection;
  16.  
  17. internal Enumerator (MyIntList collection)
  18. {
  19. this.collection = collection;
  20. }
  21.  
  22. public int Current { get { return collection.data [currentIndex]; } }
  23. object IEnumerator.Current { get { return Current; } }
  24.  
  25. public bool MoveNext()
  26. {
  27. return ++currentIndex < collection.data.Length;
  28. }
  29.  
  30. public void Reset() { currentIndex = -1; }
  31.  
  32. // Given we don’t need a Dispose method, it’s good practice to
  33. // implement it explicitly, so it’s hidden from the public interface.
  34.  
  35. void IDisposable.Dispose() {}
  36. }
  37. }

使用List<T>:

  1. List<string> words = new List<string>(); // New string-typed list
  2.  
  3. words.Add ("melon");
  4. words.Add ("avocado");
  5. words.AddRange (new string[] { "banana", "plum" } );
  6. words.Insert (0, "lemon"); // insert at
  7. words.InsertRange (0, new string[] { "peach", "nashi" }); // start
  8.  
  9. words.Remove ("melon");
  10. words.RemoveAt (3); // Remove the 4th element
  11. words.RemoveRange (0, 2); // Remove first 2 elements
  12.  
  13. // Remove all strings starting in 'n':
  14. words.RemoveAll (delegate (string s) { return s.StartsWith ("n"); });
  15.  
  16. Console.WriteLine (words [0]); // first word
  17. Console.WriteLine (words [words.Count - 1]); // last word
  18. foreach (string s in words) Console.WriteLine (s); // all words
  19. List<string> subset = words.GetRange (1, 2); // 2nd->3rd words
  20.  
  21. string[] wordsArray = words.ToArray(); // Creates a new typed array
  22.  
  23. // Copy first two elements to the end of an existing array:
  24. string[] existing = new string [1000];
  25. words.CopyTo (0, existing, 998, 2);
  26.  
  27. List<string> bigWords = words.ConvertAll <string> // Converts to
  28. (delegate (string s) { return s.ToUpper(); } ); // uppercase
  29.  
  30. List<int> lengths = words.ConvertAll <int>
  31. (delegate (string s) { return s.Length; } );

使用LinkedList<T>:

  1. LinkedList<string> tune = new LinkedList<string>();
  2. tune.AddFirst ("do"); // do
  3. tune.AddLast ("so"); // do - so
  4.  
  5. tune.AddAfter (tune.First, "re"); // do - re - so
  6. tune.AddAfter (tune.First.Next, "mi"); // do - re - mi - so
  7. tune.AddBefore (tune.Last, "fa"); // do - re - mi - fa - so
  8.  
  9. tune.RemoveFirst(); // re - mi - fa - so
  10. tune.RemoveLast(); // re - mi - fa
  11.  
  12. LinkedListNode<string> miNode = tune.Find ("mi");
  13. tune.Remove (miNode); // re - fa
  14. tune.AddFirst (miNode); // mi - re - fa
  15.  
  16. foreach (string s in tune) Console.WriteLine (s);

使用Queue<T>:

  1. Queue<int> q = new Queue<int>();
  2. q.Enqueue (10);
  3. q.Enqueue (20);
  4. int[] data = q.ToArray(); // Exports to an array
  5. Console.WriteLine (q.Count); // "2"
  6. Console.WriteLine (q.Peek()); // "10"
  7. Console.WriteLine (q.Dequeue()); // "10"
  8. Console.WriteLine (q.Dequeue()); // "20"
  9. Console.WriteLine (q.Dequeue()); // throws an exception (queue empty)

使用Stack<T>:

  1. Stack<int> s = new Stack<int>();
  2. s.Push (1); // Stack = 1
  3. s.Push (2); // Stack = 1,2
  4. s.Push (3); // Stack = 1,2,3
  5. Console.WriteLine (s.Count); // Prints 3
  6. Console.WriteLine (s.Peek()); // Prints 3, Stack = 1,2,3
  7. Console.WriteLine (s.Pop()); // Prints 3, Stack = 1,2
  8. Console.WriteLine (s.Pop()); // Prints 2, Stack = 1
  9. Console.WriteLine (s.Pop()); // Prints 1, Stack = <empty>
  10. Console.WriteLine (s.Pop()); // throws exception

使用HashSet<T>:

  1. HashSet<char> letters = new HashSet<char> ("the quick brown fox");
  2.  
  3. Console.WriteLine (letters.Contains ('t')); // true
  4. Console.WriteLine (letters.Contains ('j')); // false
  5.  
  6. foreach (char c in letters) Console.Write (c); // the quickbrownfx
  1. HashSet<char> letters = new HashSet<char> ("the quick brown fox");
  2. letters.IntersectWith ("aeiou");
  3. foreach (char c in letters) Console.Write (c); // euio
  1. HashSet<char> letters = new HashSet<char> ("the quick brown fox");
  2. letters.ExceptWith ("aeiou");
  3. foreach (char c in letters) Console.Write (c); // th qckbrwnfx
  1. HashSet<char> letters = new HashSet<char> ("the quick brown fox");
  2. letters.SymmetricExceptWith ("the lazy brown fox");
  3. foreach (char c in letters) Console.Write (c); // quicklazy

使用Dictionary<TKey,TValue>:

  1. var d = new Dictionary<string, int>();
  2.  
  3. d.Add("One", 1);
  4. d["Two"] = 2; // adds to dictionary because "two" not already present
  5. d["Two"] = 22; // updates dictionary because "two" is now present
  6. d["Three"] = 3;
  7.  
  8. Console.WriteLine (d["Two"]); // Prints "22"
  9. Console.WriteLine (d.ContainsKey ("One")); // true (fast operation)
  10. Console.WriteLine (d.ContainsValue (3)); // true (slow operation)
  11. int val = 0;
  12. if (!d.TryGetValue ("onE", out val))
  13. Console.WriteLine ("No val"); // "No val" (case sensitive)
  14.  
  15. // Three different ways to enumerate the dictionary:
  16.  
  17. foreach (KeyValuePair<string, int> kv in d) // One ; 1
  18. Console.WriteLine (kv.Key + "; " + kv.Value); // Two ; 22
  19. // Three ; 3
  20.  
  21. foreach (string s in d.Keys) Console.Write (s); // OneTwoThree
  22. Console.WriteLine();
  23. foreach (int i in d.Values) Console.Write (i); // 1223

Using SortedDictionary<TKey,TValue>:

  1. // MethodInfo is in the System.Reflection namespace
  2.  
  3. var sorted = new SortedList <string, MethodInfo>();
  4.  
  5. foreach (MethodInfo m in typeof (object).GetMethods())
  6. sorted [m.Name] = m;
  7.  
  8. foreach (string name in sorted.Keys)
  9. Console.WriteLine (name);
  10.  
  11. foreach (MethodInfo m in sorted.Values)
  12. Console.WriteLine (m.Name + " returns a " + m.ReturnType);
  13.  
  14. Console.WriteLine (sorted ["GetHashCode"]); // Int32 GetHashCode()
  15.  
  16. Console.WriteLine (sorted.Keys [sorted.Count - 1]); // ToString
  17. Console.WriteLine (sorted.Values[sorted.Count - 1].IsVirtual); // True

扩展Collection<T>:

  1. public class Animal
  2. {
  3. public string Name;
  4. public int Popularity;
  5. public Zoo Zoo { get; internal set; }
  6.  
  7. public Animal(string name, int popularity)
  8. {
  9. Name = name; Popularity = popularity;
  10. }
  11. }
  12.  
  13. public class AnimalCollection : Collection <Animal>
  14. {
  15. Zoo zoo;
  16. public AnimalCollection (Zoo zoo) { this.zoo = zoo; }
  17.  
  18. protected override void InsertItem (int index, Animal item)
  19. {
  20. base.InsertItem (index, item);
  21. item.Zoo = zoo;
  22. }
  23. protected override void SetItem (int index, Animal item)
  24. {
  25. base.SetItem (index, item);
  26. item.Zoo = zoo;
  27. }
  28. protected override void RemoveItem (int index)
  29. {
  30. this [index].Zoo = null;
  31. base.RemoveItem (index);
  32. }
  33. protected override void ClearItems()
  34. {
  35. foreach (Animal a in this) a.Zoo = null;
  36. base.ClearItems();
  37. }
  38. }
  39.  
  40. public class Zoo
  41. {
  42. public readonly AnimalCollection Animals;
  43. public Zoo() { Animals = new AnimalCollection (this); }
  44. }

扩展KeyedCollection<,>:

  1. public class Animal
  2. {
  3. string name;
  4. public string Name
  5. {
  6. get { return name; }
  7. set {
  8. if (Zoo != null) Zoo.NotifyNameChange (this, value);
  9. name = value;
  10. }
  11. }
  12. public int Popularity;
  13. public Zoo Zoo { get; internal set; }
  14.  
  15. public Animal (string name, int popularity)
  16. {
  17. Name = name; Popularity = popularity;
  18. }
  19. }
  20.  
  21. public class AnimalCollection : KeyedCollection <string, Animal>
  22. {
  23. Zoo zoo;
  24. public AnimalCollection (Zoo zoo) { this.zoo = zoo; }
  25.  
  26. internal void NotifyNameChange (Animal a, string newName)
  27. {
  28. this.ChangeItemKey (a, newName);
  29. }
  30.  
  31. protected override string GetKeyForItem (Animal item)
  32. {
  33. return item.Name;
  34. }
  35.  
  36. // The following methods would be implemented as in the previous example
  37. protected override void InsertItem (int index, Animal item)...
  38. protected override void SetItem (int index, Animal item)...
  39. protected override void RemoveItem (int index)...
  40. protected override void ClearItems()...
  41. }
  42.  
  43. public class Zoo
  44. {
  45. public readonly AnimalCollection Animals;
  46. public Zoo() { Animals = new AnimalCollection (this); }
  47. }
  48.  
  49. class Program
  50. {
  51. static void Main()
  52. {
  53. Zoo zoo = new Zoo();
  54. zoo.Animals.Add (new Animal ("Kangaroo", 10));
  55. zoo.Animals.Add (new Animal ("Mr Sea Lion", 20));
  56. Console.WriteLine (zoo.Animals [0].Popularity); // 10
  57. Console.WriteLine (zoo.Animals ["Mr Sea Lion"].Popularity); // 20
  58. zoo.Animals ["Kangaroo"].Name = "Mr Roo";
  59. Console.WriteLine (zoo.Animals ["Mr Roo"].Popularity); // 10
  60. }
  61. }
  1. 使用EqualityComparer:
  1. public class Customer
  2. {
  3. public string LastName;
  4. public string FirstName;
  5.  
  6. public Customer (string last, string first)
  7. {
  8. LastName = last;
  9. FirstName = first;
  10. }
  11. }
  12.  
  13. public class LastFirstEqComparer : EqualityComparer <Customer>
  14. {
  15. public override bool Equals (Customer x, Customer y)
  16. {
  17. return x.LastName == y.LastName && x.FirstName == y.FirstName;
  18. }
  19.  
  20. public override int GetHashCode (Customer obj)
  21. {
  22. return (obj.LastName + ";" + obj.FirstName).GetHashCode();
  23. }
  24. }
  25.  
  26. static void Main()
  27. {
  28. Customer c1 = new Customer ("Bloggs", "Joe");
  29. Customer c2 = new Customer ("Bloggs", "Joe");
  30.  
  31. // Because we’ve not overridden object.Equals, normal reference
  32. // type equality semantics apply:
  33.  
  34. Console.WriteLine (c1 == c2); // false
  35. Console.WriteLine (c1.Equals (c2)); // false
  36.  
  37. Dictionary<Customer, string> d = new Dictionary<Customer, string>();
  38. d [c1] = "Joe";
  39. Console.WriteLine (d.ContainsKey (c2)); // false
  40.  
  41. // Now with the custom equality comparer:
  42.  
  43. LastFirstEqComparer eq = new LastFirstEqComparer();
  44. d = new Dictionary<Customer, string> (eq);
  45. d [c1] = "Joe";
  46. Console.WriteLine (d.ContainsKey (c2)); // true
  47. }

使用IComparer接口:

  1. class Wish
  2. {
  3. public string Name;
  4. public int Priority;
  5.  
  6. public Wish (string name, int priority)
  7. {
  8. Name = name;
  9. Priority = priority;
  10. }
  11. }
  12.  
  13. class PriorityComparer : Comparer <Wish>
  14. {
  15. public override int Compare (Wish x, Wish y)
  16. {
  17. if (object.Equals (x, y)) return 0; // Fail-safe check
  18. return x.Priority.CompareTo (y.Priority);
  19. }
  20. }
  1. static void Main()
  2. {
  3. List<Wish> wishList = new List<Wish>();
  4. wishList.Add (new Wish ("Peace", 2));
  5. wishList.Add (new Wish ("Wealth", 3));
  6. wishList.Add (new Wish ("Love", 2));
  7. wishList.Add (new Wish ("3 more wishes", 1));
  8.  
  9. wishList.Sort (new PriorityComparer());
  10. foreach (Wish w in wishList) Console.Write (w.Name + " | ");
  11. }

SurnameComparer:

  1. class SurnameComparer : Comparer <string>
  2. {
  3. StringComparer strCmp;
  4.  
  5. public SurnameComparer (CultureInfo ci)
  6. {
  7. // Create a case-sensitive, culture-sensitive string comparer
  8. strCmp = StringComparer.Create (ci, false);
  9. }
  10.  
  11. string Normalize (string s)
  12. {
  13. s = s.Trim();
  14. if (s.ToUpper().StartsWith ("MC")) s = "MAC" + s.Substring (2);
  15. return s;
  16. }
  17.  
  18. public override int Compare (string x, string y)
  19. {
  20. // Directly call Compare on our culture-aware StringComparer
  21. return strCmp.Compare (Normalize (x), Normalize (y));
  22. }
  23. }

C#3.0 集合的更多相关文章

  1. yii2.0 集合七牛SDK 上传图片到第三方

    首先,请用composer下载七牛phpSDK (具体参考官方文档) composer require qiniu/php-sdk 注册七牛账号 获取 AK SK(密匙) ,创建资源对象 获取doma ...

  2. Underscore.js (1.7.0)-集合(Collections)(25)

    稽核函数(数组或对象) each_.each(list, iteratee, [context]) 别名: forEach 遍历list中的所有元素,按顺序用遍历输出每个元素.如果传递了context ...

  3. MongoDB shell 0 集合方法

    方法名 描述 db.collection.aggregate() 聚合,主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果 db.collection.bulkWrite() 批量写入 ...

  4. 【集合框架】JDK1.8源码分析之LinkedList(七)

    一.前言 在分析了ArrayList了之后,紧接着必须要分析它的同胞兄弟:LinkedList,LinkedList与ArrayList在底层的实现上有所不同,其实,只要我们有数据结构的基础,在分析源 ...

  5. 【集合框架】JDK1.8源码分析之Collections && Arrays(十)

    一.前言 整个集合框架的常用类我们已经分析完成了,但是还有两个工具类我们还没有进行分析.可以说,这两个工具类对于我们操作集合时相当有用,下面进行分析. 二.Collections源码分析 2.1 类的 ...

  6. Java 集合 - ArrayList

    源码分析 属性 // 默认的初始化容量 private static final int DEFAULT_CAPACITY = 10; // 用于无参构造中初始化一个空数组 private stati ...

  7. Python 集合(set)使用

    1.python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差 ...

  8. [黑马程序员] 集合框架2——Map系 & 集合工具类(Collections、Arrays)

    ---------------------- ASP.Net+Android+IO开发..Net培训.期待与您交流! ---------------------- 0. 集合框架按其所实现的接口, 大 ...

  9. JavaScript一个集合的运算类

    输出都在控制台中: <script type="text/javascript"> function Set() { //这是一个构造函数 this.values = ...

随机推荐

  1. MariaDB-5.5.32源码编译安装

    MariaDB数据库管理系统是MySQL的一个分支,主要由开源社区在维护,采用GPL授权许可.开发这个分支的原因之一是:Oracle公司收购了MySQL后,有将MySQL闭源的潜在风险,因此社区采用分 ...

  2. uml 在需求分析阶段的应用

    上一篇博客写了uml在软件开发过程中的应用,这以篇要详细介绍一下UML在需求分析过程中的应用. 以机房收费系统为例进行讲解,先介绍一个该系统. 首先该系统的用户分为三个等级,一般用户,操作员,管理员, ...

  3. fastjson把对象转化成json避免$ref

    转自http://blog.csdn.net/wxwzy738/article/details/30244993 DisableCircularReferenceDetect来禁止循环引用检测: JS ...

  4. idea生成JAVADOC 报java.lang.IllegalArgumentException解决方案[终极]

    idea生成javadoc文档,总是会报  java.lang.IllegalArgumentException     at sun.net.www.ParseUtil.decode(ParseUt ...

  5. 【Cocos2d-X开发学习笔记】第09期:渲染框架之菜单类(CCMenu)的使用

    本系列学习教程使用的是cocos2d-x-2.1.4(最新版为3.0alpha0-pre) ,PC开发环境Windows7,C++开发环境VS2010    一.菜单项(CCMenuItem) 菜单项 ...

  6. cocos2d-x 基本数学

    转自:http://cjhworld.blog.163.com/blog/static/207078036201331510141222/ 数学函数: ccp(x, y); // 以坐标x,y创建一个 ...

  7. 【24】若所有参数皆需类型转换,请为此采用non-members函数

    1.令class支持隐式类型转换,往往是个糟糕的主意.但有些情况是合理的,比如数值类型.考虑,有理数Rational有分子,分母两个字段,缺省参数值为0,1.Ration a = 2;我们期望构造一个 ...

  8. ThinkPHP CURD方法盘点:page方法

    page方法也是模型的连贯操作方法之一,是完全为分页查询而诞生的一个人性化操作方法. 用法 我们在前面已经了解了关于limit方法用于分页查询的情况,而page方法则是更人性化的进行分页查询的方法,例 ...

  9. BAE3.0还不支持本地写入文件

    BAE3.0对比2.0做了很大的改动,对于安装应用方面也方便了很多,普通的应用表面上(下文就是讲为什么说表面上)不需要做什么适配.比如wp博客,直接修改wp-config.php,把数据库信息填一下就 ...

  10. android实现弧形进度表盘效果

    附件:Cirbar.rar