简体   繁体   中英

How to write String.Contains in Dynamic Linq

I'm trying to write a dynamic linq query like:

var q = obj.Where("message.Contains('hello')");

I know it works for

var q = obj.Where(o => o.message.Contains('hello'));

but i'm looking for dynamic linq solution

Thanks.

现在找到我的答案。

var q = obj.Where("message.Contains(@0)", "hello");

I know this isn't what you are looking for, but just as a point to consider:

Depending on how many various kinds of operation you expect to perform, I would create a switch statement to handle this.

As an example, some pseudocode using an enum:

(OperationType is an Enum if desired)

private object example(OperationType optype, Object obj, String match)
{
   var q;
   switch (optype)
        {
        case OperationType.Contains:
            q = obj.Where(o => o.message.Contains(match));
        break;
        case OperationType.EndsWith:
            q = obj.Where(o => o.message.EndsWith(match));
        break;
        case OperationType.StartsWith:
            q = obj.Where(o => o.message.StartsWith(match));
        break;
    }
    return q;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM