From ac280ea73317db0429d405a25161bcd1fcb82ade Mon Sep 17 00:00:00 2001 From: Elivo Date: Tue, 28 Oct 2025 11:04:35 +0800 Subject: [PATCH] =?UTF-8?q?TextUtility.Distinct=20=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=E5=80=BC=E6=94=B9=E4=B8=BA=E6=95=B0=E7=BB=84=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Apewer/TextUtility.cs | 32 +++++++++++++------------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/Apewer/TextUtility.cs b/Apewer/TextUtility.cs index aa41f64..5dd5fca 100644 --- a/Apewer/TextUtility.cs +++ b/Apewer/TextUtility.cs @@ -2,6 +2,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; @@ -657,18 +658,18 @@ namespace Apewer } /// 对字符串列表去重。指定 valid 参数时将去除无效字符串。 - public static List Distinct(IEnumerable strings, bool valid = false) + /// + /// + public static string[] Distinct(IEnumerable strings, bool valid = false) { - if (strings == null) return new List(); + if (strings == null) return new string[0]; const string space = " "; - - var count = strings.Count(); - var array = new string[count]; - var added = 0; var hasNull = false; var hasEmpty = false; var hasSpace = false; + + var array = new ArrayBuilder(); foreach (var s in strings) { if (s == null) @@ -676,8 +677,7 @@ namespace Apewer if (valid) continue; if (hasNull) continue; hasNull = true; - array[added] = s; - added += 1; + array.Add(s); continue; } if (s == Empty) @@ -685,8 +685,7 @@ namespace Apewer if (valid) continue; if (hasEmpty) continue; hasEmpty = true; - array[added] = s; - added += 1; + array.Add(s); continue; } if (s == space) @@ -694,13 +693,12 @@ namespace Apewer if (valid) continue; if (hasSpace) continue; hasSpace = true; - array[added] = s; - added += 1; + array.Add(s); continue; } var exist = false; - for (var i = 0; i < added; i++) + for (var i = 0; i < array.Length; i++) { if (array[i] == s) { @@ -710,14 +708,10 @@ namespace Apewer } if (exist) continue; - array[added] = s; - added += 1; + array.Add(s); } - if (added < 1) return new List(); - var list = new List(added); - for (var i = 0; i < added; i++) list.Add(array[i]); - return list; + return array.Export(); } /// 约束字符串中的字符,只包含指定的字符。