C#语言。
需实现List<string>只允许插入100条记录。
如果List中已经存在100条记录,当再插入记录时,则将最先插入的记录自动被删除掉,进而保证List中只有最近插入的100条记录。以下简图为例:
List中已经存在100条记录了。当再次插入记录“zzz”时,保留新插入的记录“zzz”,自动删除掉索引 0 的“aaa”。请问这该如何高效的实现呢?谢谢List中的值|索引
----------------------
|aaa|       0
|bbb|       1
|ccc|       2
|ddd|       3
|eee|       4
 ...
 ...
|kkk|       100ListC#队列

解决方案 »

  1.   

    List中已经存在100条记录了。当再次插入记录“zzz”时,保留新插入的记录“zzz”,自动删除掉最先插入的索引 0 的“aaa”。
      

  2.   

    你自己写一个class,内部用string[100]不是更好?
      

  3.   

     List<string> lst = new List<string>(100);
    ...           //插入新数据时
                if (lst.Count == 100)
                {
                    lst.RemoveAt(0);
                }
                lst.Add(newstr);
      

  4.   

    List<string> li;
    li.RemoveAt(0);
    li.Add("zzz");很简单啊,一边删除,一边添加
      

  5.   

    先判断一下是否到达最大边界 if(list.count==100)li.RemoveAt(0);li.Add("zzz");
      

  6.   

    有Queue<T>干嘛非要用List<T>去当队列呢,真不明白为什么好多人喜欢这么用。
      

  7.   

    用Queue<T>Represents a first-in, first-out collection of objects.
    http://msdn.microsoft.com/en-us/library/system.collections.queue.aspxList  舔舔减减,性能很差的。
      

  8.   


    请教:List和Queue 的Contains性能对比如何?谢谢
      

  9.   

    List<string> lst = new List<string>(100);
    ...           //插入新数据时
                if (lst.Count == 100)
                {
                    lst.RemoveAt(0);
                }
                lst.Add(newstr); 这个方法好呀!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      

  10.   

    LZ要的是最佳效率
    既然队列有固定数量,还是自己写的好public class CustomQueue<T>
    {
        private T[] _Array;
        private int current, setter;    public CustomQueue(int size)
        {
            if (size <= 0)
                throw new IndexOutOfRangeException();
            _Array = new T[size];
            current = 0;
            setter = 0;
        }    public void Enqueue(T item)
        {
            _Array[setter] = item;
            setter++;
            if (setter == _Array.Length)
                setter = 0;
            if (setter == current)
                current++;
            if (current == _Array.Length)
                current = 0;
        }    public T Dequeue()
        {
            if (current == setter)
                return default(T);
            T item = _Array[current];
            _Array[current] = default(T);
            current++;
            if (current == _Array.Length)
                current = 0;
            return item;
        }
    }