[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 333
  • Last Modified:

I need to create an extension that completes Contains

Hello,

   How can I create an extension to convert a string in many conditions in the Where part of a Linq. Look at this example:

   from x in data where x.name.MyFunction("john Mary")...

   My function should translate this to:

   from x in data where x.name.Contains("john") || x.name.Contains("Mary") ...

   I belive that the extension is like this, but I'm stuck!

  public MyFunction(string str)
  {
    foreach (var element in str.ToUpper().Split(" "))
    {
        ....            
    }
}

  Can someone help me?

  Thanks,
  Marco Castro
0
MarcoCastro
Asked:
MarcoCastro
  • 3
1 Solution
 
jasonduanCommented:
To create an extension method, you need create a static class.


public static class MyExtensionClass
{
     public static bool MyContains(this string str)
     {
        foreach (var element in str.ToUpper().Split(" "))
        {
            ....            
        }
    }
}



Note: "Contains" is already a method of string provided by .net framework, so you need use a different name other than "Contains"
0
 
Carl TawnSystems and Integration DeveloperCommented:
If you wanted to call your method "Include" then you could use:
    public static class Helpers
    {
        public static bool Includes(this string source, string value)
        {
            string[] values = value.Split(' ');
            foreach (string val in values)
                if (source.Contains(val))
                    return true;

            return false;
        }
    }

Open in new window

0
 
MarcoCastroAuthor Commented:
Carl,

  I need something like this. Your code don't works because the Linq Entity (I use FireBird) don't know how to transle this code to a SQL statement. Isn't possible to return a Linq Contains based function? Like this:

   data.Includes("a b")

   should returns

   data.Contains("a") || data.Contans("b") -- this code will de translated by the Linq Entity

   Thanks,
   Marco Castro
0
 
MarcoCastroAuthor Commented:
0
 
MarcoCastroAuthor Commented:
I got the answer to my question by myself.
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now