将列表中不需要的字符替换为其他列表中已定义的字符
本文关键字:字符 列表 定义 其他 替换 不需要 | 更新日期: 2023-09-27 18:01:03
我有两个List<T>
集合。一个用于用户搜索首选项,另一个用于不需要的字符。要求将第一个列表中不需要的字符替换为第二个列表中定义的字符。
我只是通过循环浏览第一个列表来完成替换。然后在循环中,通过第二个列表开始另一次迭代,并替换每个不需要的字符。
public class Test
{
public void DoTest()
{
//For test purpose, create the filter list.
var filterList = new List<Filter>
{
new Filter(){ Column="UserName", Value="O'Connor", Operator="start-with"},
new Filter(){ Column="SRCount", Value="2", Operator="Equal"}
};
//Replace the unwanted chars(like single quotes with double) in search string.
UnwantedCharReplacement(filterList);
}
private void UnwantedCharReplacement(IList<Filter> filters)
{
//Get the list of 'Filter' class which contains the unwanted chars.
var lists = from filter in filters
where UnwantedCharacterList.All.Any(c => filter.Value.Contains(c.Key))
select filter;
//Loop through each 'Filter' list
foreach (var list in lists)
{
//Loop through available unwanted char list, then replace.
UnwantedCharacterList.All.ForEach(u =>
{
list.Value = list.Value.Replace(u.Key, u.Value);
});
}
}
}
/// <summary>
/// This class is using for holding the user's search preferences.
/// </summary>
public class Filter
{
public string Column { get; set; }
public string Operator { get; set; }
public string Value { get; set; }
}
/// <summary>
/// This class using for replacing characters like single quotes...etc in search string.
/// </summary>
internal static class UnwantedCharacterList
{
public static KeyValuePair<string, string> Apostrophe = new KeyValuePair<string, string>("'", "''");
public static List<KeyValuePair<string, string>> All
{
get { return new List<KeyValuePair<string, string>> { Apostrophe }; }
}
}
所以我想知道是否有一种更优化的方法可以让我获得更好的性能?
您的foreach
循环不会有任何效果,因为您的list.Value
不属于任何列表。要保存更改,lists
变量需要是List<>或阵列。不过,修复起来很容易——如果您有意的话,请对原始查询调用.ToList
。此外,您一直在谈论"char"替换,但您的UnwantedCharacterList包含单个字符串。从技术上讲,它们并不相同。
现在,如果我们讨论替换,而不是在foreach
循环中,您可以使用.Aggregate
:
list.Value = UnwantedCharacterList.All
.Aggregate(list.Value, (result, replacement) =>
result.Replace(replacement.Key, replacement.Value);
如果您需要将"不需要的"字符替换到位,那么您必须坚持使用外部foreach
循环。如果你可以返回一个新的序列,那么你可以使用一个查询:
var replaced = filterList.Select(filter =>
new Filter
{
Column = filter.Column,
Value = UnwantedCharacterList.All
.Aggregate(list.Value, (result, replacement) =>
result.Replace(replacement.Key, replacement.Value),
Operator = filter.Operator
});
我可能还会在UnwantedCharacterList
中创建一个单独的方法,该方法将包含.Aggregate
调用。
编辑:我建议使用外部foreach
循环进行就地更改的速度有点太快了。当然,您需要使用List
的.ForEach()
方法。