简体   繁体   English

在Linq查询中使用自定义扩展方法

[英]Using Custom Extension Methods Inside Linq Query

I have made my custom In extension method as shown below: 我已经制作了自定义的In扩展方法,如下所示:

 public static class ExtensionMethods
    {
        public static bool In(this string str, IEnumerable<String> list)
        {
            foreach (var s in list)
            {
                if (s.Equals(str)) return true; 
            }

            return false; 
        }
    }

And now I like to use it with my LINQ query. 现在,我想在LINQ查询中使用它。 What can I do and how do I use it? 我该怎么办以及如何使用它?

I think your method is very similar to Enumerable.Contains. 我认为您的方法与Enumerable.Contains非常相似。 Perhaps you could just use that instead. 也许您可以只使用它。

If you really want to use your method then it will work fine in a LINQ to Objects query, but it won't be possible to use it in a database query. 如果您真的想使用您的方法,那么它将在LINQ to Objects查询中很好地工作,但是在数据库查询中将无法使用它。

You should be able to say 你应该可以说

if (stringName.In(listVariableName)){....}

unless the class ExtensionMethods is on a different namespace. 除非类ExtensionMethods位于其他名称空间上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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