C# 清除IList所有对象包含指定的字符
C# 全选
/// <summary>
/// 清除IList所有对象包含指定的字符
/// </summary>
public static class ListCleaner
{
// 缓存:类型 => 可读写字符串属性
private static readonly ConcurrentDictionary<Type, PropertyInfo[]> _stringPropertyCache = new();
/// <summary>
/// 泛型强类型:清理列表中所有对象字符串属性的指定字符
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="list">数据列表</param>
/// <param name="charsToRemove">要删除的字符</param>
public static void RemoveText(this IList list, params char[] charsToRemove)
{
if (list == null || list.Count == 0 || charsToRemove == null || charsToRemove.Length == 0)
return;
var removeSet = new HashSet<char>(charsToRemove);
var type = list[0].GetType();
var props = GetStringProperties(type);
foreach (var item in list)
{
if (item == null) continue;
foreach (var prop in props)
{
string? val = (string?)prop.GetValue(item);
if (string.IsNullOrEmpty(val)) continue;
// 快速过滤字符
var span = val.AsSpan();
char[] buf = new char[span.Length];
int idx = 0;
foreach (char c in span)
{
if (!removeSet.Contains(c))
buf[idx++] = c;
}
prop.SetValue(item, new string(buf, 0, idx));
}
}
}
/// <summary>
/// 获取类型 T 中所有可读写字符串属性(缓存)
/// </summary>
private static PropertyInfo[] GetStringProperties(Type type)
{
return _stringPropertyCache.GetOrAdd(type, t =>
t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanRead && p.CanWrite && p.PropertyType == typeof(string))
.ToArray()
);
}
}版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网





