Jon Koeter가 더 이상 존재하지 않는 다른 대답으로 블로그 게시물에서 올린 코드를 사용하기 시작했습니다.
그러나 실제로는 제대로 작동하지 않는 것으로 나타났습니다. 특히 IEnumerable
을 사용할 때 특히 그렇습니다. 즉, ToArray
을 사용하여 열거 형을 해결하고 내장 함수가 아닌 일치하는 정규식을 사용했습니다.
필자는 일단 필터링을 마친 후에 IEnumerable
을 해결하기를 원했기 때문에 IQueryable
으로 변환 한 다음 나머지 코드를 사용하여 올바른 Entity Framework 메서드를 찾고 호출합니다. 이렇게하면 쿼리 자체는 나중에 데이터베이스에 대해 호출되지 않으므로 정규식을 사용하지 않아도됩니다.
public static IQueryable<T> WhereLike<T>(this IQueryable<T> source, Expression<Func<T, string>> valueSelector, string value, char wildcard)
{
return source.Where(BuildLikeExpression(valueSelector, value, wildcard));
}
public static IEnumerable<T> WhereLike<T>(this IEnumerable<T> source, Expression<Func<T, string>> valueSelector, string value, char wildcard)
{
return source.AsQueryable().WhereLike(valueSelector, value, wildcard);
}
private static Expression<Func<T, bool>> BuildLikeExpression<T>(Expression<Func<T, 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<T, bool>>(body, parameter);
}
private static MethodInfo GetLikeMethod(string value, char wildcard)
{
var methodName = "Equals";
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";
}
var stringType = typeof(string);
return stringType.GetMethod(methodName, new[] { stringType });
}
사용법 : 내 문제가 아니라 .contains 문에, 다른 곳처럼
// example data set
var data = new List<Person> {
new Person{FirstName="John", LastName="Smith"},
new Person{FirstName="Jane", LastName="Doe"}
};
data.WhereLike(x=>x.FirstName, "John", "%"); // returns John Smith
data.WhereLike(x=>x.FirstName, "J%", "%"); // returns John Smith and Jane Smith
더 밀접하게 내 문제를보고하면, 그것은 보인다. – sslepian