Просмотр исходного кода

ref: 迁移 ToDictionary、ConcurrentList

龙腾猫跃 6 месяцев назад
Родитель
Сommit
608ab6fd7f
3 измененных файлов с 46 добавлено и 3 удалено
  1. 22 3
      Extensions/EnumerableExtensions.cs
  2. 22 0
      General/ConcurrentList.cs
  3. 2 0
      MeloongCore.csproj

+ 22 - 3
Extensions/EnumerableExtensions.cs

@@ -1,6 +1,4 @@
-using System.Collections.Concurrent;
-
-namespace MeloongCore.Extensions;
+namespace MeloongCore.Extensions;
 public static class EnumerableExtensions {
 
     #region Distinct
@@ -159,6 +157,27 @@ public static class EnumerableExtensions {
 
     #endregion
 
+    #region Dictionary
+
+    /// <summary>
+    /// 从 <see cref="ConcurrentDictionary{TKey, TValue}"/> 中移除具有指定键的元素。
+    /// 返回是否确实移除了元素。
+    /// </summary>
+    public static bool Remove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key) => dict.TryRemove(key, out _);
+
+    /// <summary>
+    /// 将二维数组转换为字典。
+    /// </summary>
+    public static Dictionary<T, T> ToDictionary<T>(this T[,] arr) where T : notnull {
+        Dictionary<T, T> result = [];
+        if (arr.Length == 0) return result;
+        if (arr.GetLength(1) != 2) throw new ArgumentException("数组必须为两列,第一列为 Key,第二列为 Value。");
+        for (int i = 0; i < arr.GetLength(0); i++) result[arr[i, 0]] = arr[i, 1];
+        return result;
+    }
+
+    #endregion
+
     /// <summary>
     /// 判断集合是否有且仅有一个元素。
     /// 在输入 null 时返回 false。

+ 22 - 0
General/ConcurrentList.cs

@@ -0,0 +1,22 @@
+namespace MeloongCore;
+public class ConcurrentList<T> : SynchronizedCollection<T>, IEnumerable, IEnumerable<T> {
+
+    // 构造函数
+    public ConcurrentList() : base() { }
+    public ConcurrentList(IEnumerable<T> data) : base(new object(), data) { }
+    public static implicit operator ConcurrentList<T>(List<T> data) => new(data);
+    public static implicit operator List<T>(ConcurrentList<T> data) => new(data);
+
+    // 对枚举器进行覆写,返回一个临时副本
+    public new IEnumerator<T> GetEnumerator() {
+        lock (SyncRoot) {
+            return Items.ToList().GetEnumerator();
+        }
+    }
+    IEnumerator IEnumerable.GetEnumerator() {
+        lock (SyncRoot) {
+            return Items.ToList().GetEnumerator();
+        }
+    }
+
+}

+ 2 - 0
MeloongCore.csproj

@@ -24,6 +24,7 @@
 
 	<ItemGroup>
 	  <Reference Include="PresentationFramework" />
+	  <Reference Include="System.ServiceModel" />
 	</ItemGroup>
 
 	<ItemGroup>
@@ -37,6 +38,7 @@
 		<Using Include="System.IO" />
 		<Using Include="System.Net" />
 		<Using Include="System.Threading" />
+		<Using Include="System.Collections.Concurrent" />
 		<Using Include="System.Runtime.CompilerServices" />
 		<Using Include="System.Runtime.InteropServices" />
 		<Using Include="MeloongCore.Extensions" />