替换 .Net Standard 2.0 中的 string.Contains(string, StringComparison)

far*_*izi 3 c# .net-core .net-standard

考虑以下代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个 .Net Standard 2.0 类型的项目,我想在其中使用上面的代码。但问题是无法使用这种重载:

.Contains method (query, StringComparison.InvariantCultureIgnoreCase)
Run Code Online (Sandbox Code Playgroud)

它不存在。而在 .NET Core 项目中,则没有问题。对于该Contains()方法的重载,您有解决方案或替代方案吗?

Jon*_*eet 7

您可以使用IndexOfaStringComparison,然后检查结果是否为非负数:

string text = "BAR";
bool result = text.IndexOf("ba", StringComparison.InvariantCultureIgnoreCase) >= 0;
Run Code Online (Sandbox Code Playgroud)

可能会有一些非常小众的情况(例如用零宽不连字字符),在那里他们将得到不同的结果,但是我希望他们在相当于几乎所有的情况下。话虽如此,GitHub 上.NET Core 代码表明Contains无论如何都是以这种方式实现的。