MarcoCastro
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
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
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;
}
}
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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I got the answer to my question by myself.
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"