2

I have a string like:

"bottle 750 green"

The string has a variable number of words each time. I need , based on this string to create:

CONTAINS(descr_en,'"*bottle*" and "*750*" and "*green*"')

I will then attach this to a where clause on an sql statement in order to get the desired results.

How can i create the resulting contains clause?

I have tried this:

var str = "mara 750 bottle";
    string[] strarr = str.Split(' ');
    var result = "";
    foreach (var s in strarr)
    {
        result += "\"*" + s + "*\"" + " AND ";
    }

This gives me : "*mara*" AND "*750*" AND "*bottle*" AND which is almost what i need.

The only thing i need from the above is to get rid of the training " AND "...

I prefer a clean solution based on LINQ if possible.

3 Answers 3

3
string.Join(" AND ", "mara 750 bottle".Split(' ').Select (s => string.Format("\"*{0}*\"", s)))

gives "*mara*" AND "*750*" AND "*bottle*"

Sign up to request clarification or add additional context in comments.

Comments

0

Here is a fairly clean method.

public string BuildContainsClause(string filter)
{
    var keywords = filter
        .Split(' ')
        .Select(e => string.Format("\"*{0}*\"", e));

    return string.Format("CONTAINS(descr_en,'{0}')", string.Join(" AND ", keywords));
}

Usage:

var contains = BuildContainsClause("bottle 750 green");
// contains = "CONTAINS(descr_en,'\"*bottle*\" AND \"*750*\" AND \"*green*\"')"

Comments

0

/*Why not just build your CONTAINS clause based on:

//This is not literally suitable.
foreach( string s in samplestring.Split(' '))
{
    yourstringbuilder.append(" and *");
    yourstringbuilder.append(s);
    yourstringbuilder.append("*");
}

?*/

EDIT: For your edited question - just result = result.remove(result.Length - " AND ".Length); after your loop

1 Comment

I updated my question as i think i am doing what you say BUT i need to get rid of the ending AND...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.