From 110db553fd42c6aeb1ae083abaf475cb10e4abcd Mon Sep 17 00:00:00 2001
From: FalconFly <12919280+falconfly@user.noreply.gitee.com>
Date: Tue, 30 Apr 2024 15:53:39 +0800
Subject: [PATCH] =?UTF-8?q?=E5=AE=9A=E9=95=BF=E6=9C=89=E5=BA=8F=E5=88=97?=
=?UTF-8?q?=E8=A1=A8=E7=B1=BB?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Falcon.SugarApi/FixedLengthStortedList.cs | 89 +++++++++++++++++++++++
1 file changed, 89 insertions(+)
create mode 100644 Falcon.SugarApi/FixedLengthStortedList.cs
diff --git a/Falcon.SugarApi/FixedLengthStortedList.cs b/Falcon.SugarApi/FixedLengthStortedList.cs
new file mode 100644
index 0000000..e882960
--- /dev/null
+++ b/Falcon.SugarApi/FixedLengthStortedList.cs
@@ -0,0 +1,89 @@
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Falcon.SugarApi
+{
+ ///
+ /// 固定长度,有序列表
+ ///
+ public class FixedLengthStortedList:IEnumerable, ICollection
+ {
+ ///
+ /// 数据列表
+ ///
+ public List List { get; private set; }
+ ///
+ /// 长度
+ ///
+ public int Length { get; set; }
+
+ int ICollection.Count => (this.List as ICollection).Count;
+
+ bool ICollection.IsReadOnly => (this.List as ICollection).IsReadOnly;
+
+ ///
+ /// 通过提供长度初始化列表
+ ///
+ ///
+ public FixedLengthStortedList(int length) {
+ this.List ??= new List(length);
+ this.Length = length;
+ }
+
+ IEnumerator IEnumerable.GetEnumerator() {
+ return (this.List as IEnumerable).GetEnumerator();
+ }
+
+ IEnumerator IEnumerable.GetEnumerator() {
+ return (this.List as IEnumerable).GetEnumerator();
+ }
+ private static object _lockObj = new object();
+
+ void ICollection.Add(T item) {
+ lock(_lockObj) {
+ this.List.Add(item);
+ RemoveMoreItems();
+ }
+ }
+
+ ///
+ /// 增加列表项目
+ ///
+ /// 新添加的项目
+ /// 定长排序列表
+ public FixedLengthStortedList Add(T[] items) {
+ lock(_lockObj) {
+ this.List.AddRange(items);
+ RemoveMoreItems();
+ }
+ return this;
+ }
+
+ ///
+ /// 增加列表项目
+ ///
+ /// 新添加的项目
+ /// 定长排序列表
+ public FixedLengthStortedList Add(IEnumerable items) {
+ return Add(items.ToArray());
+ }
+
+ void ICollection.Clear() => this.List.Clear();
+
+ bool ICollection.Contains(T item) => this.List.Contains(item);
+
+ void ICollection.CopyTo(T[] array,int arrayIndex) => this.List.CopyTo(array,arrayIndex);
+
+ bool ICollection.Remove(T item) => this.List.Remove(item);
+
+ ///
+ /// 从头部移除多余的元素
+ ///
+ private void RemoveMoreItems() {
+ while(this.List.Count > this.Length) {
+ this.List.RemoveAt(0);
+ }
+ }
+ }
+}