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

public class MyGenCollection : IEnumerable<int>
{
int[] data = {1, 2, 3}; public IEnumerator<int> GetEnumerator()
{
foreach (int i in data)
yield return i;
} IEnumerator IEnumerable.GetEnumerator() // Explicit implementation
{ // keeps it hidden.
return GetEnumerator();
}
}

直接实现IEnumerable<T>:

class MyIntList : IEnumerable<int>
{
int[] data = { 1, 2, 3 }; // The generic enumerator is compatible with both IEnumerable and
// IEnumerable<T>. We implement the nongeneric GetEnumerator method
// explicitly to avoid a naming conflict. public IEnumerator<int> GetEnumerator() { return new Enumerator(this); }
IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this); } class Enumerator : IEnumerator<int>
{
int currentIndex = -1;
MyIntList collection; internal Enumerator (MyIntList collection)
{
this.collection = collection;
} public int Current { get { return collection.data [currentIndex]; } }
object IEnumerator.Current { get { return Current; } } public bool MoveNext()
{
return ++currentIndex < collection.data.Length;
} public void Reset() { currentIndex = -1; } // Given we don’t need a Dispose method, it’s good practice to
// implement it explicitly, so it’s hidden from the public interface. void IDisposable.Dispose() {}
}
}

使用List<T>:

List<string> words = new List<string>();    // New string-typed list

words.Add ("melon");
words.Add ("avocado");
words.AddRange (new string[] { "banana", "plum" } );
words.Insert (0, "lemon"); // insert at
words.InsertRange (0, new string[] { "peach", "nashi" }); // start words.Remove ("melon");
words.RemoveAt (3); // Remove the 4th element
words.RemoveRange (0, 2); // Remove first 2 elements // Remove all strings starting in 'n':
words.RemoveAll (delegate (string s) { return s.StartsWith ("n"); }); Console.WriteLine (words [0]); // first word
Console.WriteLine (words [words.Count - 1]); // last word
foreach (string s in words) Console.WriteLine (s); // all words
List<string> subset = words.GetRange (1, 2); // 2nd->3rd words string[] wordsArray = words.ToArray(); // Creates a new typed array // Copy first two elements to the end of an existing array:
string[] existing = new string [1000];
words.CopyTo (0, existing, 998, 2); List<string> bigWords = words.ConvertAll <string> // Converts to
(delegate (string s) { return s.ToUpper(); } ); // uppercase List<int> lengths = words.ConvertAll <int>
(delegate (string s) { return s.Length; } );

使用LinkedList<T>:

LinkedList<string> tune = new LinkedList<string>();
tune.AddFirst ("do"); // do
tune.AddLast ("so"); // do - so tune.AddAfter (tune.First, "re"); // do - re - so
tune.AddAfter (tune.First.Next, "mi"); // do - re - mi - so
tune.AddBefore (tune.Last, "fa"); // do - re - mi - fa - so tune.RemoveFirst(); // re - mi - fa - so
tune.RemoveLast(); // re - mi - fa LinkedListNode<string> miNode = tune.Find ("mi");
tune.Remove (miNode); // re - fa
tune.AddFirst (miNode); // mi - re - fa foreach (string s in tune) Console.WriteLine (s);

使用Queue<T>:

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

使用Stack<T>:

Stack<int> s = new Stack<int>();
s.Push (1); // Stack = 1
s.Push (2); // Stack = 1,2
s.Push (3); // Stack = 1,2,3
Console.WriteLine (s.Count); // Prints 3
Console.WriteLine (s.Peek()); // Prints 3, Stack = 1,2,3
Console.WriteLine (s.Pop()); // Prints 3, Stack = 1,2
Console.WriteLine (s.Pop()); // Prints 2, Stack = 1
Console.WriteLine (s.Pop()); // Prints 1, Stack = <empty>
Console.WriteLine (s.Pop()); // throws exception

使用HashSet<T>:

HashSet<char> letters = new HashSet<char> ("the quick brown fox");

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

使用Dictionary<TKey,TValue>:

var d = new Dictionary<string, int>();

d.Add("One", 1);
d["Two"] = 2; // adds to dictionary because "two" not already present
d["Two"] = 22; // updates dictionary because "two" is now present
d["Three"] = 3; Console.WriteLine (d["Two"]); // Prints "22"
Console.WriteLine (d.ContainsKey ("One")); // true (fast operation)
Console.WriteLine (d.ContainsValue (3)); // true (slow operation)
int val = 0;
if (!d.TryGetValue ("onE", out val))
Console.WriteLine ("No val"); // "No val" (case sensitive) // Three different ways to enumerate the dictionary: foreach (KeyValuePair<string, int> kv in d) // One ; 1
Console.WriteLine (kv.Key + "; " + kv.Value); // Two ; 22
// Three ; 3 foreach (string s in d.Keys) Console.Write (s); // OneTwoThree
Console.WriteLine();
foreach (int i in d.Values) Console.Write (i); // 1223

Using SortedDictionary<TKey,TValue>:

// MethodInfo is in the System.Reflection namespace

var sorted = new SortedList <string, MethodInfo>();

foreach (MethodInfo m in typeof (object).GetMethods())
sorted [m.Name] = m; foreach (string name in sorted.Keys)
Console.WriteLine (name); foreach (MethodInfo m in sorted.Values)
Console.WriteLine (m.Name + " returns a " + m.ReturnType); Console.WriteLine (sorted ["GetHashCode"]); // Int32 GetHashCode() Console.WriteLine (sorted.Keys [sorted.Count - 1]); // ToString
Console.WriteLine (sorted.Values[sorted.Count - 1].IsVirtual); // True

扩展Collection<T>:

public class Animal
{
public string Name;
public int Popularity;
public Zoo Zoo { get; internal set; } public Animal(string name, int popularity)
{
Name = name; Popularity = popularity;
}
} public class AnimalCollection : Collection <Animal>
{
Zoo zoo;
public AnimalCollection (Zoo zoo) { this.zoo = zoo; } protected override void InsertItem (int index, Animal item)
{
base.InsertItem (index, item);
item.Zoo = zoo;
}
protected override void SetItem (int index, Animal item)
{
base.SetItem (index, item);
item.Zoo = zoo;
}
protected override void RemoveItem (int index)
{
this [index].Zoo = null;
base.RemoveItem (index);
}
protected override void ClearItems()
{
foreach (Animal a in this) a.Zoo = null;
base.ClearItems();
}
} public class Zoo
{
public readonly AnimalCollection Animals;
public Zoo() { Animals = new AnimalCollection (this); }
}

扩展KeyedCollection<,>:

public class Animal
{
string name;
public string Name
{
get { return name; }
set {
if (Zoo != null) Zoo.NotifyNameChange (this, value);
name = value;
}
}
public int Popularity;
public Zoo Zoo { get; internal set; } public Animal (string name, int popularity)
{
Name = name; Popularity = popularity;
}
} public class AnimalCollection : KeyedCollection <string, Animal>
{
Zoo zoo;
public AnimalCollection (Zoo zoo) { this.zoo = zoo; } internal void NotifyNameChange (Animal a, string newName)
{
this.ChangeItemKey (a, newName);
} protected override string GetKeyForItem (Animal item)
{
return item.Name;
} // The following methods would be implemented as in the previous example
protected override void InsertItem (int index, Animal item)...
protected override void SetItem (int index, Animal item)...
protected override void RemoveItem (int index)...
protected override void ClearItems()...
} public class Zoo
{
public readonly AnimalCollection Animals;
public Zoo() { Animals = new AnimalCollection (this); }
} class Program
{
static void Main()
{
Zoo zoo = new Zoo();
zoo.Animals.Add (new Animal ("Kangaroo", 10));
zoo.Animals.Add (new Animal ("Mr Sea Lion", 20));
Console.WriteLine (zoo.Animals [0].Popularity); // 10
Console.WriteLine (zoo.Animals ["Mr Sea Lion"].Popularity); // 20
zoo.Animals ["Kangaroo"].Name = "Mr Roo";
Console.WriteLine (zoo.Animals ["Mr Roo"].Popularity); // 10
}
}
使用EqualityComparer:
public class Customer
{
public string LastName;
public string FirstName; public Customer (string last, string first)
{
LastName = last;
FirstName = first;
}
} public class LastFirstEqComparer : EqualityComparer <Customer>
{
public override bool Equals (Customer x, Customer y)
{
return x.LastName == y.LastName && x.FirstName == y.FirstName;
} public override int GetHashCode (Customer obj)
{
return (obj.LastName + ";" + obj.FirstName).GetHashCode();
}
} static void Main()
{
Customer c1 = new Customer ("Bloggs", "Joe");
Customer c2 = new Customer ("Bloggs", "Joe"); // Because we’ve not overridden object.Equals, normal reference
// type equality semantics apply: Console.WriteLine (c1 == c2); // false
Console.WriteLine (c1.Equals (c2)); // false Dictionary<Customer, string> d = new Dictionary<Customer, string>();
d [c1] = "Joe";
Console.WriteLine (d.ContainsKey (c2)); // false // Now with the custom equality comparer: LastFirstEqComparer eq = new LastFirstEqComparer();
d = new Dictionary<Customer, string> (eq);
d [c1] = "Joe";
Console.WriteLine (d.ContainsKey (c2)); // true
}

使用IComparer接口:

class Wish
{
public string Name;
public int Priority; public Wish (string name, int priority)
{
Name = name;
Priority = priority;
}
} class PriorityComparer : Comparer <Wish>
{
public override int Compare (Wish x, Wish y)
{
if (object.Equals (x, y)) return 0; // Fail-safe check
return x.Priority.CompareTo (y.Priority);
}
}
static void Main()
{
List<Wish> wishList = new List<Wish>();
wishList.Add (new Wish ("Peace", 2));
wishList.Add (new Wish ("Wealth", 3));
wishList.Add (new Wish ("Love", 2));
wishList.Add (new Wish ("3 more wishes", 1)); wishList.Sort (new PriorityComparer());
foreach (Wish w in wishList) Console.Write (w.Name + " | ");
}

SurnameComparer:

class SurnameComparer : Comparer <string>
{
StringComparer strCmp; public SurnameComparer (CultureInfo ci)
{
// Create a case-sensitive, culture-sensitive string comparer
strCmp = StringComparer.Create (ci, false);
} string Normalize (string s)
{
s = s.Trim();
if (s.ToUpper().StartsWith ("MC")) s = "MAC" + s.Substring (2);
return s;
} public override int Compare (string x, string y)
{
// Directly call Compare on our culture-aware StringComparer
return strCmp.Compare (Normalize (x), Normalize (y));
}
}

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. 大数据架构师基础:hadoop家族,Cloudera产品系列等各种技术

    大数据我们都知道hadoop,可是还会各种各样的技术进入我们的视野:Spark,Storm,impala,让我们都反映不过来.为了能够更好的架构大数据项目,这里整理一下,供技术人员,项目经理,架构师选 ...

  2. HW5.31

    import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner i ...

  3. adb 启动失败的原因和修改adb端口号

    在我们使用Android Studio的时候,有时候就会出现adb打开失败或者启动不了的情况. adb 启动失败的原因:有其他程序占用了adb默认启动的端口号(像我就遇到过,每次只要提前启动了酷狗音乐 ...

  4. [转]常用的130个vim命令

    原帖地址:http://www.oschina.net/news/43167/130-essential-vim-commands 从 1970 年开始,vi 和 vim 就成为了程序员最喜爱的文本编 ...

  5. HDU5791--Two (DP)

    题意:两个数列a,b,求相同的子序列有多少对,内容相同位置不同也算不同. 题解:dp[i][j]表示a数列前i个数个 b数列前j个数 有多少对 递推方程: dp[i][j] = dp[i-1][j-1 ...

  6. EventBus使用小记

    自从使用了EventBus,代码干净了好多. 从此你不用startActivityForResult了,从此你不用再写注册BroadcastReceiver了,从此你不用再写一些回调了. 只需要在需要 ...

  7. 第2组UI组件:TextView及其子类

    1 TextView及其子类的继承关系 TextView直接继承自View,是EditView与Button两个类的父类,如下为TextView各子类继承关系. 2 个UI的样式图 CheckedTe ...

  8. 上struts2的xml在&lt;result type=&quot;redirect&quot;&gt;参数问题

    今天做项目,我遇到了一个精彩的问题. 我需要在struts的xml中的<action>的<result>中配置type="redirect".同一时候须要传 ...

  9. InSAR在地面沉降监测中的应用及发展前景

    合成孔径雷达(Synthetic Aperture Radar,SAR)的概念始于20世纪50年代,是正在发展中的极具潜力的微波遥感技术.SAR具有全天时.全天候的工作能力,能够穿透云层,对某些地物具 ...

  10. CSS字体大小设置时的参考(转)

    from:http://blog.sina.com.cn/s/blog_51cd580b0100gg6y.html font-size 设置的绝对关键字: 以下几个绝对字体大小的设置是有效的.当然他们 ...