从 LINQ 循环中的字符串中删除重音 - Ucommerce 产品

Remove accents from string in LINQ loop - Ucommerce products

我必须从 ucommerce 产品中搜索密钥(产品)。

这是代码-

string whatToSearch = "L'oreal";

var normalizedText = whatToSearch.Normalize(NormalizationForm.FormD);

whatToSearch = nonSpacingMarkRegex.Replace(normalizedText, string.Empty);

whatToSearch = Regex.Replace(whatToSearch, @"[^0-9a-zA-Z ]+", "");

var products = new List<UCommerce.EntitiesV2.Product>();

if (!string.IsNullOrWhiteSpace(whatToSearch))
{
    products = UCommerce.EntitiesV2.Product.Find(p =>
            p.VariantSku == null && p.DisplayOnSite &&
            (
                p.Sku.Contains(whatToSearch)
                || p.Name.RemoveDiacritics().Contains(whatToSearch)
                || p.ProductDescriptions.Any(
                    d => d.DisplayName.Contains(whatToSearch)
                         || d.ShortDescription.Contains(whatToSearch)
                         || d.LongDescription.Contains(whatToSearch)
                )
            )
    );
}

 var productIds = products.Select(x => x.Id).ToList();

这是我在循环中使用的扩展方法。

public static string RemoveDiacritics(this string s)
{
    var normalizedString = s.Normalize(NormalizationForm.FormD);
    var stringBuilder = new StringBuilder();

    foreach (var c in normalizedString)
    {
        if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
            stringBuilder.Append(c);
    }

    return stringBuilder.ToString();
}

我遇到了这个异常System.String RemoveDiacritics(System.String)

谁能帮忙。

谢谢

你的问题不清楚,但最可能的原因是这一行:

|| p.Name.RemoveDiacritics().Contains(whatToSearch)

我认为此代码正在联系数据库以根据查询获取产品,翻译器找不到 SQL 类似于 RemoveDiacritics() 的函数。

编辑:- 当然,如果可行的话会慢很多,但我们还是试试吧:

if (!string.IsNullOrWhiteSpace(whatToSearch))
{
    //I've added call to ALL to fetch all products and then filter on 
    //code side. 
    products = UCommerce.EntitiesV2.Product.All().Where(p =>
            p.VariantSku == null && p.DisplayOnSite &&
            (
                p.Sku.Contains(whatToSearch)
                || p.Name.RemoveDiacritics().Contains(whatToSearch)
                || p.ProductDescriptions.Any(
                    d => d.DisplayName.Contains(whatToSearch)
                         || d.ShortDescription.Contains(whatToSearch)
                         || d.LongDescription.Contains(whatToSearch)
                )
            )
    );
}