在.Net Standard 2.0中替换string.Containsstring,StringComparison

问题描述

请考虑以下代码

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,然后检查结果是否为负数:

string text = "BAR";
bool result = text.IndexOf("ba",StringComparison.InvariantCultureIgnoreCase) >= 0;

可能,在某些特殊情况下(例如具有零宽度的非联接字符),它们会给出不同的结果,但我希望它们会在几乎所有情况下都是等效的。话虽如此,.NET Core code on GitHub暗示Contains正是以这种方式实现的。

,

Jon的答案正确,我只需要验证他的答案,并且Contains的实现在IndexOf中使用.NET Framework。您可以做的是将扩展添加到.NET Standard中未包括的任何方法。

对于您的Contains,扩展名是:

public static bool Contains(this string str,string value,StringComparison comparison)
{
    return str.IndexOf(value,comparison) >= 0;
}

您可以对重置执行相同的操作。如果需要更多实现细节,可以签出Microsoft Reference,这将使您对.NET底层实现有很好的了解。