简体   繁体   中英

Using Custom Extension Methods Inside Linq Query

I have made my custom In extension method as shown below:

 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. What can I do and how do I use it?

I think your method is very similar to 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.

You should be able to say

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

unless the class ExtensionMethods is on a different namespace.

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