手机版
你好,游客 登录 注册
背景:
阅读新闻

C#常用集合的使用

[日期:2014-02-17] 来源:Linux社区  作者:Linux [字体:大 中 小]

四、链表

LinkedList是一个双向链表,链表有个有点,就是在链表中间插入、删除元素很快,但是查找中间与末尾的元素很慢,需要一个节点一个节点的去找。

    [Serializable]
    [DebuggerTypeProxy(typeof(System_CollectionDebugView<>))]
    [DebuggerDisplay("Count = {Count}")]
    [ComVisible(false)]
    public class LinkedList<T> : ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISerializable, IDeserializationCallback

由此可见链表也是有集合的特性的,可以迭代,同时还有链表的特性

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    public class Program
    {
        static void Main(string[] args)
        {
            LinkedList<String> lList = new LinkedList<string>();
            LinkedListNode<String> node = new LinkedListNode<string>("root");
            lList.AddFirst(node);
            node = lList.AddAfter(node, "张三");
            node = lList.AddAfter(node, "李四");
            node = lList.AddAfter(node, "王五");
            node = lList.AddAfter(node, "田六");
            node = lList.AddAfter(node, "赵七");

            foreach (String item in lList)
            {
                Console.WriteLine("foreach迭代:" + item);
            }

            node = lList.First;
            Console.WriteLine("第一个元素:" + node.Value);
            node = lList.Last;
            Console.WriteLine("最后一个元素:" + node.Value);
            Console.Read();
        }
    }
}

五、有序列表

SortedList采用键-值对存储,键不能重复,并且会根据key进行排序

    [Serializable]
    [DebuggerTypeProxy(typeof(System_DictionaryDebugView<,>))]
    [DebuggerDisplay("Count = {Count}")]
    [ComVisible(false)]
    public class SortedList<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable

可以看出SortedList不仅具有字典的特性,还有集合,迭代的功能

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    public class Program
    {
        static void Main(string[] args)
        {
            //Key必须唯一,如果不唯一可以考虑Lookup<TKey,TElement>
            SortedList<int, String> sList = new SortedList<int, string>();
            sList.Add(100, "张三");
            sList.Add(21, "李四");
            sList.Add(13, "王五");
            sList.Add(44, "田六");
            sList.Add(35, "赵七");

            foreach (KeyValuePair<int, String> item in sList)
            {
                Console.WriteLine("key=" + item.Key.ToString() + ";value=" + item.Value);
            }

            Console.Read();
        }
    }
}

linux
相关资讯       C#  C#集合 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款