1. 概述

  本章内容包括 .net平台中的集合、如何选择集合 以及 如何实现自定义集合。

2. 主要内容

  2.1 使用数组(Array)

int[] arrayOfInt = new int[]; 

for (int x = ; x < arrayOfInt.Length; x++)
{
    arrayOfInt[x] = x;
} foreach (int i in arrayOfInt) //实现了IEnumerable
{
    Console.Write(i); // Displays 0123456789
}

    .net中还支持多维数组和锯齿(jagged)数组

string[,] array2D = new string[, ] { { “one”, “two” }, { “three”, “four” },
                        { “five”, “six” } }; int[][] jaggedArray = 
   {
        new int[] {,,,,},
        new int[] {,,,},
        new int[] {,}
    };

  2.2 理解泛型和非泛型版本

    *使用值类型作为泛型参数的时候,要注意可能会发生的装箱情况。比如值类型未实现IEquatable<T>或IComparable<T>的时候。

  2.3 使用列表(List)

    List<T>的定义:

public class List<T> : IList<T>, ICollection<T>, IList, ICollection, 
IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable

    其中IList<T> 和 ICollection<T> 的定义如下:

public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
{
        T this[int index] { get; set; }
        int IndexOf(T item);
void Insert(int index, T item);    
        void RemoveAt(int index);
}
public interface ICollection<T> : IEnumerable<T>, IEnumerable
{
        int Count { get; }    
        bool IsReadOnly { get; }
        void Add(T item);    
        void Clear();    
        bool Contains(T item);    
        void CopyTo(T[] array, int arrayIndex);    
        bool Remove(T item);
}

    下面是使用List<T>操作数据项的示例:

List<string> listOfStrings =
    new List<string> { “A”, “B”, “C”, “D”, “E” }; for (int x = ; x < listOfStrings.Count; x++)
    Console.Write(listOfStrings[x]); // Displays: ABCDE listOfStrings.Remove(“A”); Console.WriteLine(listOfStrings[]); // Displays: B listOfStrings.Add(“F”); Console.WriteLine(listOfStrings.Count); // Displays: 5 bool hasC = listOfStrings.Contains(“C”); Console.WriteLine(hasC); // Displays: true

  2.4 使用字典(Dictionary)

    字典由键值对组成,可以根据键获取值。不允许重复的键。字典的定义:

public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>,
ICollection<KeyValuePair<TKey, TValue>>, IDictionary, ICollection,
IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>,
IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, ISerializable,
IDeserializationCallback

    字典的使用示例:

Person p1 = new Person { Id = , Name = “Name1” };
Person p2 = new Person { Id = , Name = “Name2” };
Person p3 = new Person { Id = , Name = “Name3” }; var dict = new Dictionary<int, Person>();
dict.Add(p1.Id, p1);
dict.Add(p2.Id, p2);
dict.Add(p3.Id, p3); foreach (KeyValuePair<int, Person> v in dict)
{
    Console.WriteLine(“{}: {}”, v.Key, v.Value.Name);
} dict[] = new Person { Id = , Name = “Name4” }; Person result;
if (!dict.TryGetValue(, out result))
{
    Console.WriteLine(“No person with a key of  can be found”);
}

  2.5 使用集(sets)

    sets是一个非重复的,无序集合。C#中set是系统保留关键字,可以使用HastSet<T>,它实现了ISet<T>。

public interface ISet<T> : ICollection<T>, IEnumerable<T>, IEnumerable
{
bool Add(T item);
void ExceptWith(IEnumerable<T> other);
void IntersectWith(IEnumerable<T> other);
bool IsProperSubsetOf(IEnumerable<T> other);
bool IsProperSupersetOf(IEnumerable<T> other);
bool IsSubsetOf(IEnumerable<T> other);
bool IsSupersetOf(IEnumerable<T> other);
bool Overlaps(IEnumerable<T> other);
bool SetEquals(IEnumerable<T> other);
void SymmetricExceptWith(IEnumerable<T> other);
void UnionWith(IEnumerable<T> other);
}

    使用HashSet<T>的示例:

public void UseHashSet()
{
    HashSet<int> oddSet = new HashSet<int>();
    HashSet<int> evenSet = new HashSet<int>();     for (int x = ; x <= ; x++)
    {
        if (x %  == )
            evenSet.Add(x);
        else
            oddSet.Add(x);
    }     DisplaySet(oddSet);
    DisplaySet(evenSet);     oddSet.UnionWith(evenSet);
    DisplaySet(oddSet);
} private void DisplaySet(HashSet<int> set)
{
    Console.Write(“{“);
    foreach (int i in set)
    {
        Console.Write(“ {}”, i);
    }
    Console.WriteLine(“ }”);
}

  2.6 使用队列(queue)和堆栈(stack)

    队列主要用于临时存储数据,遵循先进先出的原则。三个重要的方法是:Enqueue、Dequeue、Peek。

Queue<string> myQueue = new Queue<string>();
myQueue.Enqueue(“Hello”);
myQueue.Enqueue(“World”);
myQueue.Enqueue(“From”);
myQueue.Enqueue(“A”);
myQueue.Enqueue(“Queue”); foreach (string s in myQueue)
    Console.Write(s + “ “);
// Displays: Hello World From A Queue

    堆栈 遵循先进后出的原则。也具有跟队列类似的三个方法:Push、Pop、Peek。

Stack<string> myStack = new Stack<string>();
myStack.Push(“Hello”);
myStack.Push(“World”);
myStack.Push(“From”);
myStack.Push(“A”);
myStack.Push(“Queue”); foreach (string s in myStack)
    Console.Write(s + “ “);
// Displays: Queue A From World Hello

  2.7 选择合适的集合

    各个集合间最大的不同是 元素的访问方式:

    ① 列表和字典都支持元素的随机访问。字典提供了更快的元素读取速度,但是不能存储重复的数据项。

    ② 队列和堆栈提供了特定顺序的元素访问方式。元素取出后就自动从集合删除了。

    ③ 基于Set的集合,在元素比较方面有一些特性。但是不提供元素的随机访问。

  2.8 创建自定义集合

    .net提供的集合相关的接口包括: IEnumerable、IEnumerable<T>、IList<T>、ICollection<T>、IDictionary<TKey,TValue>、

    ICollection<TKey,TValue>、ISet<T>。

    也可以继承现有的集合对象来添加自定义的方法:

public class PeopleCollection : List<Person>
{
    public void RemoveByAge(int age)
    {
        for (int index = this.Count - ; index >= ; index--)
        {
            if (this[index].Age == age)
            {
                this.RemoveAt(index);
            }
        }
    }     public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        foreach (Person p in this)
        {
            sb.AppendFormat(“{} {} is {}”, p.FirstName, p.LastName, p.Age);
        }
        return sb.ToString();
    }
}

3. 总结

  ① .net提供了泛型和非泛型的集合版本,使用的时候,优先选择泛型版本。

  ② 数组(Array)是最基础的集合,是定长的。

  ③ 列表(List)是使用最多的集合,是变长的。

  ④ 字典(Dictionary)是存取键值对的集合。

  ⑤ HashSet保存唯一项并提供相应的操作。

  ⑥ 队列是先进先出的集合。

  ⑦ 堆栈是先进后出的集合。

  ⑧ 可以通过实现指定的接口或者继承现有的集合来自定义集合类型。

第二十二章 数据访问(In .net4.5) 之 集合的更多相关文章

  1. 第十九章 数据访问(In .net4.5) 之 处理数据

    1. 概述 本章介绍 数据库.Json和Xml.web services 三种介质上的数据操作. 2. 主要内容 2.1 数据库 ① 建立连接 .net平台中的数据连接类都继承自DbConnectio ...

  2. 《Linux命令行与shell脚本编程大全》 第二十二章 学习笔记

    第二十二章:使用其他shell 什么是dash shell Debian的dash shell是ash shell的直系后代,ash shell是Unix系统上原来地Bourne shell的简化版本 ...

  3. 第二十二章 Django会话与表单验证

    第二十二章 Django会话与表单验证 第一课 模板回顾 1.基本操作 def func(req): return render(req,'index.html',{'val':[1,2,3...]} ...

  4. 第二十二章 跳出循环-shift参数左移-函数的使用 随堂笔记

    第二十二章 跳出循环-shift参数左移-函数的使用 本节所讲内容: 22.1 跳出循环 22.2 Shift参数左移指令 22.3 函数的使用 22.4 实战-自动备份mysql数据库和nginx服 ...

  5. Gradle 1.12用户指南翻译——第二十二章. 标准的 Gradle 插件

    其他章节的翻译请参见: http://blog.csdn.net/column/details/gradle-translation.html 翻译项目请关注Github上的地址: https://g ...

  6. 20190925 On Java8 第二十二章 枚举

    第二十二章 枚举 基本 enum 特性 创建 enum 时,编译器会为你生成一个相关的类,这个类继承自 Java.lang.Enum. valueOf() 是在 Enum 中定义的 static 方法 ...

  7. Introduction to 3D Game Programming with DirectX 12 学习笔记之 --- 第二十二章:四元数(QUATERNIONS)

    原文:Introduction to 3D Game Programming with DirectX 12 学习笔记之 --- 第二十二章:四元数(QUATERNIONS) 学习目标 回顾复数,以及 ...

  8. “全栈2019”Java多线程第二十二章:饥饿线程(Starvation)详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...

  9. “全栈2019”Java异常第二十二章:try-with-resources语句详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java异 ...

随机推荐

  1. js捕获回车事件,并且获取每一条输入内容

    <body> <div style="width: 200px; height: 20px;"> <textarea id="inputVa ...

  2. 1、程序启动原理和UIApplication【转】

    一.UIApplication 1.简单介绍 (1)UIApplication对象是应用程序的象征,一个UIApplication对象就代表一个应用程序. (2)每一个应用都有自己的UIApplica ...

  3. JavaScript对象的创建之基于原型方式

    原型内存模型介绍 原型是javascript中非常特殊的一个对象,当一个函数创建之后,会随之就产生一个原型对象. 当通过这个函数的构造函数创建一个具体的对象之后,在这个具体的对象中就会有一个属性指向原 ...

  4. Eclipse is running in a JRE, but a JDK is required 解决方法

    本文非原创,转自http://liguoliang.com/2010/eclipse-is-running-in-a-jre-but-a-jdk-is-required/ 安装Maven后每次启动出现 ...

  5. [工具] 如何利用Notepad++去除重复行

    问题: 需要去除重复数据, 例如: 解决方案: 1. 打开notepad++: 2. 如果没有找到"TextFx" 选项, 需要先安装该插件. 依次打开"插件" ...

  6. 一步一步学习Unity3d学习笔记系1.2 单机游戏和网游的数据验证概念

    这一次的笔记的主要内容是单机和网游的数据存储,数据验证方式,在游戏的时候除了控制角色的行动,还涉及到用户角色的升级,经验,金钱赚取,道具购买,技能升级 等等一些数据的交易, 那么单机游戏和网游的区别如 ...

  7. 常见行为:仿真&重力&碰撞&捕捉

    一.UIDynamic是从iOS 7开始引入的一种新技术,隶属于UIKit框架.可以认为是一种物理引擎,能模拟和仿真现实生活中的物理现象,重力.弹性碰撞等,游戏开发中很常见,例如愤怒的小鸟. 二.UI ...

  8. DNS协议 实践

    根据DNS协议发送UDP请求,然后获取IP地址 头文件: #ifndef __DNS__ #define __DNS__ #include <stdio.h> #include <s ...

  9. Java基础——clone()方法浅析

    一.clone的概念 clone顾名思义就是复制, 在Java语言中, clone方法被对象调用,所以会复制对象.所谓的复制对象,首先要分配一个和源对象同样大小的空间,在这个空间中创建一个新的对象.那 ...

  10. 华为OJ平台——整数的二进制中1的个数

    题目描述: 输入一个整数,求该整数的二进制表达中有多少个1.例如输入10,由于其二进制表示为1010,有两个1,因此输出2. 思路: 这是一道很基本的考查位运算的面试题.包括微软在内的很多公司都曾采用 ...