如何在LINQ中使用*进行搜索

本文关键字:搜索 LINQ | 更新日期: 2023-09-27 18:10:42

我想用*搜索。我有

 <asp:TextBox runat="server" Width="500" Height="20" ID="tbInfo"></asp:TextBox>

搜索方法:当我搜索没有星号*是正常搜索,但当我设置星号* LINQ查询像tbInfo.Contains()

的例子:

I set in textbox: Michael - 1 result, 
I set in textbox: Michael* - 20 results
我希望有人能理解我。10 x

如何在LINQ中使用*进行搜索

您必须自己编写一些代码。

示例查询:

var q = (from c in db.Customers
         where c.CompanyName.Contains(name)
         select c)
        .ToList();

上面的示例将始终在CompanyName中的任何位置搜索a匹配。但是你需要给你的用户更多的控制权方法,允许它们在任一处提供通配符要匹配的文本的开头或结尾。这意味着你只能的存在和位置动态构建查询通配符字符。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
    public static class LinqExtensions
    {
        public static IQueryable<TSource> WhereLike<TSource>(
            this IQueryable<TSource> source,
            Expression<Func<TSource, string>> valueSelector,
            string value,
            char wildcard)
        {
            return source.Where(BuildLikeExpression(valueSelector, value, wildcard));
        }
        public static Expression<Func<TElement, bool>> BuildLikeExpression<TElement>(
            Expression<Func<TElement, string>> valueSelector,
            string value,
            char wildcard)
        {
            if (valueSelector == null)
                throw new ArgumentNullException("valueSelector");
            var method = GetLikeMethod(value, wildcard);
            value = value.Trim(wildcard);
            var body = Expression.Call(valueSelector.Body, method, Expression.Constant(value));
            var parameter = valueSelector.Parameters.Single();
            return Expression.Lambda<Func<TElement, bool>>(body, parameter);
        }
        private static MethodInfo GetLikeMethod(string value, char wildcard)
        {
            var methodName = "Contains";
            var textLength = value.Length;
            value = value.TrimEnd(wildcard);
            if (textLength > value.Length)
            {
                methodName = "StartsWith";
                textLength = value.Length;
            }
            value = value.TrimStart(wildcard);
            if (textLength > value.Length)
            {
                methodName = (methodName == "StartsWith") ? "Contains" : "EndsWith";
                textLength = value.Length;
            }
            var stringType = typeof(string);
            return stringType.GetMethod(methodName, new Type[] { stringType });
        }
    }

WhereLike扩展方法的用法如下:

var searchTerm = "*Inc";
var q = db.Customers
        .WhereLike(c => c.CompanyName, searchTerm, '*')
        .ToList();

源代码在这里找到。