首頁 >後端開發 >C++ >如何在 C# 中使用多個關鍵字和 Lambda 表達式來有效過濾清單?

如何在 C# 中使用多個關鍵字和 Lambda 表達式來有效過濾清單?

Susan Sarandon
Susan Sarandon原創
2025-01-21 11:46:12481瀏覽

How Can I Efficiently Filter a List Using Multiple Keywords with a Lambda Expression in C#?

使用Lambda表達式高效過濾包含多個關鍵字的清單

你需要在一個資料庫欄位中搜尋多個關鍵字。這可以透過類似這樣的SQL查詢來實現:

<code class="language-sql">select * from MainList
where Comment like '%keyword1%'
or Comment like '%keyword2%'
... 以此类推,直到最后一个关键词。</code>

在C#中,你可以這樣做:

<code class="language-csharp">var newList = MainList
   .FilterByItems(keywords, (m, k) => m.Comments.Contains(k), true)
   .ToList();</code>

以下是FilterByItems擴充方法的實作:

<code class="language-csharp">public static class QueryableExtensions
{
    public static IQueryable<T> FilterByItems<T, TItem>(this IQueryable<T> query, IEnumerable<TItem> items,
        Expression<Func<T, TItem, bool>> filterPattern, bool isOr)
    {
        Expression? predicate = null;
        foreach (var item in items)
        {
            var itemExpr = Expression.Constant(item);
            var itemCondition = ExpressionReplacer.Replace(filterPattern.Body, filterPattern.Parameters[1], itemExpr);
            if (predicate == null)
                predicate = itemCondition;
            else
            {
                predicate = Expression.MakeBinary(isOr ? ExpressionType.OrElse : ExpressionType.AndAlso, predicate,
                    itemCondition);
            }
        }

        predicate ??= Expression.Constant(false);
        var filterLambda = Expression.Lambda<Func<T, bool>>(predicate, filterPattern.Parameters[0]);

        return query.Where(filterLambda);
    }

    class ExpressionReplacer : ExpressionVisitor
    {
        readonly IDictionary<Expression, Expression> _replaceMap;

        public ExpressionReplacer(IDictionary<Expression, Expression> replaceMap)
        {
            _replaceMap = replaceMap ?? throw new ArgumentNullException(nameof(replaceMap));
        }

        [return: NotNullIfNotNull(nameof(node))]
        public override Expression? Visit(Expression? node)
        {
            if (node != null && _replaceMap.TryGetValue(node, out var replacement))
                return replacement;
            return base.Visit(node);
        }

        public static Expression Replace(Expression expr, Expression toReplace, Expression toExpr)
        {
            return new ExpressionReplacer(new Dictionary<Expression, Expression> { { toReplace, toExpr } }).Visit(expr);
        }

        public static Expression Replace(Expression expr, IDictionary<Expression, Expression> replaceMap)
        {
            return new ExpressionReplacer(replaceMap).Visit(expr);
        }

        public static Expression GetBody(LambdaExpression lambda, params Expression[] toReplace)
        {
            if (lambda.Parameters.Count != toReplace.Length)
                throw new InvalidOperationException();

            return new ExpressionReplacer(Enumerable.Range(0, lambda.Parameters.Count)
                .ToDictionary(i => (Expression)lambda.Parameters[i], i => toReplace[i])).Visit(lambda.Body);
        }
    }
}</code>

以上是如何在 C# 中使用多個關鍵字和 Lambda 表達式來有效過濾清單?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn