3

I'm trying to implement a simple search function. I have a string array which contains all words which was typed in from the user to search. And I have another string which contains data like User Name, content... So what I want to do is to check is Name contains any of the elements in the search or String array. Right now I have a loop which checks one word at a time and concatenates the result in an IEnumerable.

Does anyone know a faster way of doing this search? Like String.ContainsAny(Search[])

11
  • Is this array pre-sorted, our does it make sense to in your case? That would change the "best" algorithm. Commented Nov 7, 2011 at 20:55
  • Its random, so the search can be Search = ["Admin", "Hello"] and I have to search through a string = "This is my post, Hello". Commented Nov 7, 2011 at 21:07
  • Without any kind of sorting, than I don't know of any algorithm that is faster than a simple linear search, as many Answers below mention with the use of Any(). Depending on when/how the array is created, and how often the array is used repeatedly without rebuilding, it may be faster to sort it first, then search with a different algorithm. But we'll need more context to your usage before we can suggest the best algorithm. Commented Nov 7, 2011 at 22:18
  • <code> s = "admin is here"; IEnumerable<Post> posts = from p in post_repository.Posts where p.Content.Contains(s) || p.Author.Contains(s) || p.ContactEmail.Contains(s) select p; </code> Commented Nov 8, 2011 at 0:46
  • The comment above is part of the code, didnt know about 5 mins to edit. I'm sorry for the horrible formatting. Thats the search I'm doing right now but the problem is that it searches for the whole phrase in string s. But I want to make it search each word. So I split the string s into parts. After that I got an array of strings. Now I have to find an efficient way of searching, thats where I'm stuck. Commented Nov 8, 2011 at 0:53

5 Answers 5

8

Try this:

Search.Any(p => name.Contains(p))
Sign up to request clarification or add additional context in comments.

5 Comments

Does anyone know a faster way of doing this search? Is that different algorithm than in question? Really faster?
As far as I know, the default object provider Any() method does a linear search until it fines one. So worst case is O(N).
I'm implementing it right now but alittle confused. What does 'p' mean in the code? Thanks
@user1034489: It's the new C# 3.0 shortcut syntax. It basically is a new method argument, that you see it used in the method body (name.Contains(p)) — that bit right there is the whole method body. Read up on how LINQ works for more info.
@user1034489 switchonthecode.com/tutorials/… msdn.microsoft.com/en-us/library/bb397687.aspx But be aware, shorter code does not make it faster
2
using System.Linq;

string[] searchItems = ...
string input = "This is the input text";

// Check whether at least one match found
bool matchFound = input.Any(w => input.Contains(w));

// Count all matches
int matchesCount = input.Where(w => input.Contains(w))
                        .Count();

1 Comment

I'm confused... searchItems is never used in your code.
1
string[] searchItems = ...;
string[] userNames = ...;

var matches = userNames.Intersect(searchItems);

You can find more about the intersect method here

Comments

1

you can do like this...

return array.Any(s => s.Equals(myString))

or try like this....

 string stringToCheck = "text1";
        string[] stringArray = { "text1", "testtest", "test1test2", "test2text1" };
        foreach (string x in stringArray)
        {
            if (x.Contains(stringToCheck))
            {
                // Process...
            }

        }

or Something like this

string stringToCheck = "text1text2text3";
string[] stringArray = new string[] { "text1" };
if (Array.Exists<string>(stringArray, (Predicate<string>)delegate(string s) { 
    return stringToCheck.IndexOf(s, StringComparison.OrdinalIgnoreCase) > -1; })) {
    Console.WriteLine("Found!");
}

1 Comment

How would you adapt your first version to allow case-invariant comparison?
0

Two solutions to this problem for example:

  1. Solution 1

    private void findDateColumn()   {
            string stringToCheck = "date";
            int stringToCheckIndex = -1;
            string elementInArray = "Not Defined or Not Found";
            if (Array.Exists<string> (headers, (Predicate<string>) delegate (string s)
            {
            stringToCheckIndex = s.IndexOf (stringToCheck,StringComparison.OrdinalIgnoreCase);
            elementInArray = s;
            return stringToCheckIndex > -1;
            }))
            {
            dateColTitle.Text = elementInArray; //a textbox to show the output
            }
    }
    
  2. Solution 2

I'm using @Lev answer, which seems simpler and shorter plus giving the same result:

    private void setDateColumnTitle ()
{

dateColTitle.Text = "Not Defined or Not Found";

var match = headers.FirstOrDefault(c => c.IndexOf("date", StringComparison.OrdinalIgnoreCase) > -1);

if (match!=null)                
    dateColTitle.Text = match;               
}

Comments

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.