【问题标题】:How to write a search for a field regardless of its case?无论大小写如何,如何编写对字段的搜索?
【发布时间】:2021-05-04 06:42:41
【问题描述】:

网站上有一个过滤器,用于通过公共属性查找值: ? propertyName = SomeName & propertyValue = SomeValue;

现在我想知道,例如,如果输入了此属性 (SomENAme1) 的错误名称会怎样 -> Web 应用程序仍会调用 SomeName 属性的过滤吗?即无论大小写都无所谓,输入的词至少与过滤器属性完全匹配?

public static IQueryable<T> ApplyFiltering<T>(this IQueryable<T> source, string propertyLabel, string propertyValue)
        
        {
            if (string.IsNullOrEmpty(propertyLabel))
            {
                return source;
            }
 
            var propertyNames = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
                                      .Where(property => property.PropertyType == typeof(string) && property.Name == propertyLabel)
                                      .Select(property => property.Name);
 
            //var predicate = PredicateBuilder.New<T>();
            Expression<Func<T, bool>> predicate = item => false;
 
            foreach (var name in propertyNames)
            {
               // if (propertyLabel.Contains(name))
               // {
                    //propertyLabel = name;
                //}
 
                predicate = predicate.Or(GetExpression<T>(name, propertyValue));
            }
 
            return source.Where(predicate);
        }

我已经在 foreach 循环中尝试过:

if (propertyLabel.ToLower().Contains(name.ToLower()))
{
    propertyLabel = name;
}

但它不起作用,即使只是小写...

【问题讨论】:

  • 在您的 LINQ 的 Where 中,您已经过滤了完全匹配。
  • ^^ 克劳斯是对的。请检查您的propertyNames 收藏的内容。你可能会发现,他们甚至不在里面。解决方案是删除&amp;&amp; property.Name == propertyLabel 并稍后检查...此处进行不区分大小写的检查。这对你来说可能很有趣:case-insensitive-ordinal-comparisons

标签: c# asp.net asp.net-web-api


【解决方案1】:
    var propertyNames = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
                              .Where(property => property.PropertyType == typeof(string)
                                && propertyLabel.ToLower().Contains(property.Name.ToLower()))
                              .Select(property => property.Name);

【讨论】:

    猜你喜欢
    • 2017-07-31
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多