定长有序列表类

This commit is contained in:
FalconFly 2024-04-30 15:53:39 +08:00
parent 80179ea54e
commit 110db553fd

View File

@ -0,0 +1,89 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Falcon.SugarApi
{
/// <summary>
/// 固定长度,有序列表
/// </summary>
public class FixedLengthStortedList<T>:IEnumerable<T>, ICollection<T>
{
/// <summary>
/// 数据列表
/// </summary>
public List<T> List { get; private set; }
/// <summary>
/// 长度
/// </summary>
public int Length { get; set; }
int ICollection<T>.Count => (this.List as ICollection<T>).Count;
bool ICollection<T>.IsReadOnly => (this.List as ICollection<T>).IsReadOnly;
/// <summary>
/// 通过提供长度初始化列表
/// </summary>
/// <param name="length"></param>
public FixedLengthStortedList(int length) {
this.List ??= new List<T>(length);
this.Length = length;
}
IEnumerator<T> IEnumerable<T>.GetEnumerator() {
return (this.List as IEnumerable<T>).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return (this.List as IEnumerable).GetEnumerator();
}
private static object _lockObj = new object();
void ICollection<T>.Add(T item) {
lock(_lockObj) {
this.List.Add(item);
RemoveMoreItems();
}
}
/// <summary>
/// 增加列表项目
/// </summary>
/// <param name="items">新添加的项目</param>
/// <returns>定长排序列表</returns>
public FixedLengthStortedList<T> Add(T[] items) {
lock(_lockObj) {
this.List.AddRange(items);
RemoveMoreItems();
}
return this;
}
/// <summary>
/// 增加列表项目
/// </summary>
/// <param name="items">新添加的项目</param>
/// <returns>定长排序列表</returns>
public FixedLengthStortedList<T> Add(IEnumerable<T> items) {
return Add(items.ToArray());
}
void ICollection<T>.Clear() => this.List.Clear();
bool ICollection<T>.Contains(T item) => this.List.Contains(item);
void ICollection<T>.CopyTo(T[] array,int arrayIndex) => this.List.CopyTo(array,arrayIndex);
bool ICollection<T>.Remove(T item) => this.List.Remove(item);
/// <summary>
/// 从头部移除多余的元素
/// </summary>
private void RemoveMoreItems() {
while(this.List.Count > this.Length) {
this.List.RemoveAt(0);
}
}
}
}