.Net Standard 2.0 中 string.Contains(string, StringComparison) 的替换
Replacement for string.Contains(string, StringComparison) in .Net Standard 2.0
考虑以下代码:
public static IQueryable<T> WhereDynamic<T>(this IQueryable<T> sourceList, string query)
{
if (string.IsNullOrEmpty(query))
{
return sourceList;
}
try
{
var properties = typeof(T).GetProperties()
.Where(x => x.CanRead && x.CanWrite && !x.GetGetMethod().IsVirtual);
//Expression
sourceList = sourceList.Where(c =>
properties.Any(p => p.GetValue(c) != null && p.GetValue(c).ToString()
.Contains(query, StringComparison.InvariantCultureIgnoreCase)));
}
catch (Exception e)
{
Console.WriteLine(e);
}
return sourceList;
}
我创建了一个 .Net Standard 2.0 类型的项目,我想在其中使用上面的代码。
但问题是无法使用此重载:
.Contains method (query, StringComparison.InvariantCultureIgnoreCase)
不存在。而在 .NET Core 项目中,则没有问题。
对于 Contains()
方法的重载,您有解决方案或替代方法吗?
可以使用IndexOf
with a StringComparison
,然后检查结果是否为non-negative:
string text = "BAR";
bool result = text.IndexOf("ba", StringComparison.InvariantCultureIgnoreCase) >= 0;
可能会有一些非常特殊的极端情况(例如 zero-width non-joiner 字符),它们会给出不同的结果,但我希望它们在 almost 所有情况下都是等效的。话虽如此,.NET Core code on GitHub 表明 Contains
正是以这种方式实现的。
Jon 有正确的答案,我只需要验证他的答案,Contains
实现在 .NET Framework
中使用 IndexOf
。您可以做的是为 .NET Standard 中未包含的任何方法添加扩展。
对于您的 Contains
扩展希望:
public static bool Contains(this string str, string value, StringComparison comparison)
{
return str.IndexOf(value, comparison) >= 0;
}
您可以对重置执行相同的操作。如果您需要更多实现细节,您可以查看 Microsoft Reference,这将使您对 .NET 底层实现有一个很好的理解。
考虑以下代码:
public static IQueryable<T> WhereDynamic<T>(this IQueryable<T> sourceList, string query)
{
if (string.IsNullOrEmpty(query))
{
return sourceList;
}
try
{
var properties = typeof(T).GetProperties()
.Where(x => x.CanRead && x.CanWrite && !x.GetGetMethod().IsVirtual);
//Expression
sourceList = sourceList.Where(c =>
properties.Any(p => p.GetValue(c) != null && p.GetValue(c).ToString()
.Contains(query, StringComparison.InvariantCultureIgnoreCase)));
}
catch (Exception e)
{
Console.WriteLine(e);
}
return sourceList;
}
我创建了一个 .Net Standard 2.0 类型的项目,我想在其中使用上面的代码。 但问题是无法使用此重载:
.Contains method (query, StringComparison.InvariantCultureIgnoreCase)
不存在。而在 .NET Core 项目中,则没有问题。
对于 Contains()
方法的重载,您有解决方案或替代方法吗?
可以使用IndexOf
with a StringComparison
,然后检查结果是否为non-negative:
string text = "BAR";
bool result = text.IndexOf("ba", StringComparison.InvariantCultureIgnoreCase) >= 0;
可能会有一些非常特殊的极端情况(例如 zero-width non-joiner 字符),它们会给出不同的结果,但我希望它们在 almost 所有情况下都是等效的。话虽如此,.NET Core code on GitHub 表明 Contains
正是以这种方式实现的。
Jon 有正确的答案,我只需要验证他的答案,Contains
实现在 .NET Framework
中使用 IndexOf
。您可以做的是为 .NET Standard 中未包含的任何方法添加扩展。
对于您的 Contains
扩展希望:
public static bool Contains(this string str, string value, StringComparison comparison)
{
return str.IndexOf(value, comparison) >= 0;
}
您可以对重置执行相同的操作。如果您需要更多实现细节,您可以查看 Microsoft Reference,这将使您对 .NET 底层实现有一个很好的理解。