Link to home
Start Free TrialLog in
Avatar of MarcoCastro
MarcoCastroFlag for Brazil

asked on

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
Avatar of jasonduan
jasonduan
Flag of United States of America image

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"
Avatar of Carl Tawn
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

Avatar of MarcoCastro

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of MarcoCastro
MarcoCastro
Flag of Brazil image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I got the answer to my question by myself.