`
wolfmaster
  • 浏览: 155586 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

c#中collection使用全攻略

    博客分类:
  • c#
阅读更多
collection非常灵活,内含很多方便的类

如往hashTable里存数据
例子:    Hashtable ht = new Hashtable();
            ht.Add("白","1Val");
            ht.Add("晓", "2Val");
            ht.Add("哲", "3Val");
            foreach(DictionaryEntry entry in ht)
            {
              Console.WriteLine(entry.Key+"->"+entry.Value);
            }


============================================================================
集合

  ((I)).集合类型
    1.一般集合
        I.Array
            a.Array中的秩是Array中的维数.一个Array可以有一个或多个秩.
              Array具有固定的容量.如果有可变容量,则用Array.CreateInstance,其可以不从零开始存储.
        II.ArrayList集合类型
            a.是数组的复杂版本.Array是数组是固定的,而ArrayList类是根据需要自动扩展的.如果更改了Array.Capacity属性的值,则自动              进行内存重新分配和元素复制.
            b.ArrayList提供添加/或移除某一范围元素的方法.在Array中,只能一次获取或设置一个元素的值.
            c.使用 Synchronized方法可以很容易地创建ArrayList的同步版本.而Array将一直保持它,直到用户实现同步为止.
            d.ArrayList提供将只读和固定大小包装返回到集合的方法.而Array不提供.
            e.Array提供ArrayList所不具有的某些灵活性.
                I.可以设置Array的下限,但ArrayList的下限始终为零.
                II.Array可以具有多个维度,而ArrayList始终是唯一的.
                III.Array是特定类型(不是Object),比ArrayList性能好.ArrayList在存储和检索时经常发生拆箱和装箱操作现象.                
        III.哈希表集合
            a.Hashtable类基于IDictionary接口,因此该集合中的每一元素是键和值对.
            b.Object.GetHashCode方法为其自身生成哈希代码.还可以通过使用Hashtable构造函数,为所有元素指定一个哈希函数.
        IV.SortedList集合类型
            a.SortedList类类似于Hashtable和ArrayList间的混合.
            b.SortedList的每一元素都是键对值,提供只返回键列表或只返回值列表的方法.
            c.如果想要一个保留键和值的集合,并且还需要索引的灵活性,则使用SortList.
        V.队列集合类型
            a.如果需要以信息在集合中存储的相同顺序来访问这些信息,请使用Queue.
            b.Enqueue将一个元素添加到Queue的队尾. Dequeue从Queue处移除最旧的元素. Peek从Queue的开始处返回最旧的元素,但不将从Queue中移除.
        VI.堆栈集合类型
            a.如果需要以信息在集合中存储的相反顺序来访问这些信息,请使用Queue.
            b.Push在Stack的顶部插入一个元素. Pop在Stack的顶部移除一个元素. Peek返回处于Stack顶部的元素,但不将其从栈顶上移除.
    2.位集合
        I.BitArray
          a.BitArray是一个集合类,容量与计数相同.通过增加Length属性来将元素添加到BitArray中;通过降低Length属性将元素删除.
          b.独特方法,如 And/Or/Xor/Not/SetAll.
          c.位于 System.Collections中.
        II.BitVector32
          a.速度快,精确存储32位,并且同时存储标志位和小整数.
          b.位于 System.Collections.Specialized中.
    3.专用集合
        I.NameValueCollection
          a.基于NameObjectCollectionBase,但NameValueCollection可以接受每个键多个值,而 NameObjectCollectionBase接受每个键,但只有一个值.
  ((2)).选择用哪种集合
    *** Queue或Stack:需要一个序列列表,其中的元素在检索后放弃.否则,用其它集合.
    *** Queue或Stack:按一定的顺序访问这些元素(先进先出,后进先出),如果随机,用其它集合.
    *** 是否通过索引访问每一个元素?
        * ArrayList和StringCollection 提供通过元素的从零开始的*索引*对其元素进行访问.
        * (Hashtable) (SortedList) (ListDictionary) (StringDictionary) 提供通过元素的*键*对其元素进行访问
        * (NameObjectCollectionBase) 和 (NameValueCollection) 提供或者通过元素的从零开始的*索引*或者通过元素的*键*对其元素进行访问.
    *** 每一元素将包含一个值/一个值和一个键的组合还是一个键和多个值的组合?
        * 一个值: 使用基于 IList 的任何集合
        * 一个键和一个值: 使用基于 IDictionary 的任何集合.
        * 一个键和多个值: 使用 System.Collections.Specialized 命名空间中的 NameValueCollection 类.
    *** 是否需要用与元素方式不同的方式对元素排序?
        * Hashtable 通过键的哈希代码对元素进行排序.
        * SortedList 基于 IComparer 实现,通过键对元素进行排序.
        * ArrayList 提供 Sort方法该方法将 IComparer 实现作为一个参数采用.
    *** 是否需要信息的快速搜索和检索?
        * 对于小集合(十项或更少),ListDictionary 快于 Hashtable.
    *** 是否需要只接受字符串的集合?
        * StringCollection (基于 IList) 和 StringDictionary (基于 IDictionary) 位于 System.Collections.Specialized 命名空间中.

============================================================================
用SortedList实现排序

using System;
using System.Collections;

namespace 集合的比较和排序
{

public class Efficience:IComparable
{
  private int workHour;
  private int outPut;
  int IComparable.CompareTo(Object obj)
  {
  if(obj==null)
    throw new ArgumentException("比较对象不能为空");
  if(!obj.GetType().Equals(this.GetType()))
    throw new ArgumentException("比较的两者类型不同");
  Efficience objEffic=(Efficience)obj;
  if(this.Effic>objEffic.Effic)
    return 1;
  if(this.Effic<objEffic.Effic)
    return -1;
  return 0;
  }
  public int WorkHour
  {
  set
  {
    if(value<0)
    throw new ArgumentException("工作时间不能为{0}或负数");
    workHour=value;
  }
  }
  public int OutPut
  {
  set
  {
    if(value<0)
    throw new ArgumentException("工作产出不能为负数");
    outPut=value;
  }
  }
  public float Effic
  {
  get
  {
    return (float)outPut/(float)workHour;
  }
  }
}
class Class1
{
  [STAThread]
  static void Main(string[] args)
  {
  Random rand=new Random();
  Efficience[] effics=new Efficience[5];
  string[] persons={"Xiaohua","Diana","YanYan","ZhuLin","LiXin"};
  Console.WriteLine("生成的 Effics 数组");
  //Console.WriteLine("effics.GetLowerBound(0)={0},effics.GetUpperBound(0)={1}",effics.GetLowerBound(0),effics.GetUpperBound(0));
  for(int i=effics.GetLowerBound(0);i<=effics.GetUpperBound(0);i++)
  {
    effics=new Efficience();
    effics.WorkHour=rand.Next()%24;
    effics.OutPut=rand.Next()%1000;
    Console.WriteLine("Person={0},Effic={1}",persons,effics.Effic);
  }

  SortedList sortedList=new SortedList();
  for(int i=effics.GetLowerBound(0);i<=effics.GetUpperBound(0);i++)
  {
    sortedList.Add(effics,persons);
  }
  Console.WriteLine("从 sortedList 中读取内容");
  foreach(Efficience effic in sortedList.GetKeyList())
  {
    Console.WriteLine("Person={0},Effic={1}",sortedList[effic],effic.Effic);
  }
  Console.Read();
  }
}
}


============================================================================
集合的拷贝
using System;
using System.Collections;
using System.Collections.Specialized;

namespace 集合的拷贝
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
  [STAThread]
  static void Main(string[] args)
  {
  NameValueCollection namedVColl=new NameValueCollection();
  namedVColl.Add("晓华","13510532686");
  namedVColl.Add("晓华","62658888");
  namedVColl.Add("小杨","1361030486");
  namedVColl.Add("小杨","62293218");
  foreach(string key in namedVColl.Keys)
    Console.WriteLine("姓名={0},电话={1}",key,namedVColl[key]);
  Console.WriteLine("拷贝后获得的命名值集合");
  string[] arr=new string[namedVColl.Count];
  namedVColl.CopyTo(arr,0);
  for(int i=arr.GetLowerBound(0);i<arr.GetUpperBound(0);i++)
  {
    Console.WriteLine("姓名={0},电话={1}",namedVColl.AllKeys,arr);
  }
  Hashtable hhtable=new Hashtable();
  hhtable["晓华"]="北京";
  hhtable["小杨"]="南京";
  Console.WriteLine("克隆前哈希表");
  foreach(object key in hhtable.Keys)
    Console.WriteLine("姓名={0},地址={1}",key,hhtable[key]);
  Hashtable hhCloned=(Hashtable)hhtable.Clone();
  hhtable["晓华"]="上海";
  Console.WriteLine("克隆修改初始化哈希表");
  foreach(object key in hhtable.Keys)
      Console.WriteLine("姓名={0},地址={1}",key,hhtable[key]);
  Console.WriteLine("修改后初始化哈希表后的克隆哈萨克希表");
  foreach(object key in hhCloned.Keys)
  {
    Console.WriteLine("姓名={0},地址={1}",key,hhCloned[key]);
  }
  Console.Read();
  }
}
}


============================================================================
集合的同步执行
using System;
using System.Collections;
using System.Collections.Specialized;

namespace 集合和同步
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
  public static void DemoLockCollection()
  {
  StringDictionary sDic=new StringDictionary() ;
  if(!sDic.IsSynchronized)
  {
    sDic.Add("晓华","花园路");
    sDic["小杨"]="新兴桥";
    foreach(string key in sDic.Keys)
    Console.WriteLine("姓名={0},地址={1}",key,sDic[key]);
  }
  else
  {
    //不采取同步处理代码
  }
  }
  [STAThread]
  static void Main(string[] args)
  {
  //以下一行代码为类DemoLockCollection()的运行
  Class1.DemoLockCollection();

  //以下代码为另一个HashTable的例程
  //创建并初始化一个哈希表
  Hashtable myHT=new Hashtable();
  myHT.Add(0,"zero");
  myHT.Add(1,"one");
  myHT.Add(2,"two");
  myHT.Add(3,"three");
  myHT.Add(4,"four");

  //创建线程安全的包装
  Hashtable mySyncdHT=Hashtable.Synchronized(myHT);

  //显示哈萨克希表的同步的状态
  Console.WriteLine("myHT{0}.",myHT.IsSynchronized ? "已经同步" : "没有同步");
  Console.WriteLine("mySncdHT{0}.",mySyncdHT.IsSynchronized ? "已经同步" : "没有同步");

  //遍历哈希
  foreach(Object key in mySyncdHT.Keys)
    Console.WriteLine("Key={0},Value={1]",key,mySyncdHT[key]);

  Console.Read();
  }
}
}

============================================================================
Array的排序(正序/逆序)
using System;

namespace Array操作
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main(string[] args)
  {
  //
  // TODO: 在此处添加代码以启动应用程序
  //
  String[] friends=new String[]{"2mojian","1zhengjian","3xugang","4guoyonghui"};
  Console.WriteLine("操作前数组数据为:");
  foreach(string index in friends)
  {
    Console.Write(index+" ");
  }
  Array.Sort(friends);
  Console.WriteLine("\n排序后的数据为:");
  for(int i=friends.GetLowerBound(0);i<=friends.GetUpperBound(0);i++)
  {
    Console.Write(friends+" ");
  }
  Array.Reverse(friends);
  Console.WriteLine("\n逆序后的数据为:");
  for(int i=friends.GetLowerBound(0);i<=friends.GetUpperBound(0);i++)
  {
    Console.Write(friends+" ");
  }
  Console.WriteLine();
  Console.Read();
  }
}
}


============================================================================
由IComparer派生的自定义比较器
(一). 说明

1.继承IComparer接口,可以自定义比较器
2.由于Array.Sort()方法接受IComparer参数,进行自定义排序规则.
  示例中也将IComparer作为Sort方法的参数,将Icomparer应用于Array.Sort()方法

(二).示例代码

using System;
using System.Collections;

namespace 比较器IComparer
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
public class Person
{
  public int ID;
  public int Age;
  public Person()
  {
  ID=0;
  Age=0;
  }
  public Person(int id,int age)
  {
  ID=id;
  Age=age;
  }
  public void Show()
  {
  Console.WriteLine("年龄={0},代号={1}",Age,ID);
  }
  public static void  ShowPersons(Person []persons)
  {
  foreach(Person person in persons)              
    Console.WriteLine("年龄={0},代号={1}",person.Age,person.ID);
  }
}
public class PersonComparer:System.Collections.IComparer
{
  int System.Collections.IComparer.Compare(object x,object y)
  {
  if(x==null||y==null)
                throw new ArgumentException("参数不能为空");
  Person temp=new Person();
  if(!x.GetType().Equals(temp.GetType())||!y.GetType().Equals(temp.GetType()))
    throw new ArgumentException("类型不一致");
  temp=null;
  Person personX=(Person)x;
  Person personY=(Person)y;
  if(personX.ID>personY.ID)
    return 1;
  if(personX.ID<personY.ID)
    return -1;
  if(personX.Age>personY.Age)
                return 1;
  if(personX.Age<personY.Age)
    return -1;
  return 0;
  }
}
class Class1
{
  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main(string[] args)
  {
  //
  // TODO: 在此处添加代码以启动应用程序
  //
  Random rand=new Random();
  Person[] persons=new Person[6];
  Console.WriteLine("随机产生的Person数组为:");
  for(int i=0;i<persons.GetLength(0);i++)
  {
    persons=new Person();
    persons.ID=rand.Next()%10;
    persons.Age=rand.Next()%50;
    persons.Show();
  }
  PersonComparer personComparer=new PersonComparer();
  //System.Collections.IComparer personComparer=new IComparer;
  Array.Sort(persons,personComparer);
  Console.WriteLine("排序后的结果:");
  Person.ShowPersons(persons);
  Person personToBeFind=new Person();
  Console.WriteLine("输入ID");
  personToBeFind.ID=int.Parse(Console.ReadLine());
  Console.WriteLine("输入Age");
  personToBeFind.Age=int .Parse(Console.ReadLine());
  int index=Array.BinarySearch(persons,personToBeFind,personComparer);
  if(index>=0)
    Console.WriteLine("待查找的元素是数组的第{0}个元素",index+1);
  else
    Console.WriteLine("对不起,没有所找的元素");
  Console.ReadLine();
  }
}
}

/////////////////////////////////////////////////////////////////////////////
hashtable  ilist

        public IList covertToIlist(Hashtable ht)
        {
            ht.Add(1,"aaaa");
            ht.Add(2,"bbbb");
            ArrayList arr = new ArrayList();
            foreach (DictionaryEntry entry in ht)
            {
                arr.Add(entry.Value);
            }
            return arr;
        }
分享到:
评论
1 楼 mooniscrazy 2008-01-12  
天哪,robin还是把这个分论坛关掉吧,受不了。

相关推荐

Global site tag (gtag.js) - Google Analytics