0

I want to search from the array. This is my code

string[] Main_Events = { "Five Ships In The Harbour", "Australia Day", "Christmas", "New Years", "The Melbourne Cup", "Australian Open Tennis" };
string search_str = "Australia Day";

string value1 = Array.Find(Main_Events, element => element.Contains(search_str));

The search works fine if i search Australia Day but if the search is The Australia Day. The value of value1 is null.

How can i search if the search value is The Australia Day and in the array the value is Australia Day then the value of value1 should be Australia Day or true.

I am using Array.Find because i want to search from 5 different arrays. Like Main_Events, i have four other arrays.

Thanks in advance

2
  • For custom search you have to create your own extension search method. I think you know why it is returning null on The Australia Day. Commented Oct 26, 2015 at 3:57
  • ok so do you mean i should use foreach to compare the values but i was using this because i have to search through 5 different arrays and then writing 5 foreach loops to search will increase the code thats why i use array.find Commented Oct 26, 2015 at 3:59

3 Answers 3

1

Try to search element in search_str:

string value1 = Array.Find(Main_Events, element => element.Contains(search_str) || search_str.Contains(element));
Sign up to request clarification or add additional context in comments.

3 Comments

Its not a generic solution. Suppose he have Football Cup and Tennis Cup. Guess what happens when you try to find 'Cup'. Also its depends on the requirement and input though :)
in such a case just use FindAll the solution will work fine . var value1 = Array.FindAll(Main_Events, element => element.Contains(search_str) || search_str.Contains(element));
@WaqarAhmed yes, it depends, but it may be an option
0

If you need the array node value to be equal to or a substring of the given string then you can change the search to below:

var value1 = Array.Find(mainEvents, element => searchStr.Contains(element));

You can change accordingly for case insensitive comparison(by converting to uppercase).

Comments

0
string[] Main_Events = { "Five Ships In The Harbour", "Australia Day", "Christmas", "New Years", "The Melbourne Cup", "Australian Open Tennis" };
string search_str = "The Australia Day";

List<string> search_strs = search_str.Split(null).Where(s => s != string.Empty).ToList();
if (search_strs.Count > 0)
{                  
    List<string> searchResult = Main_Events.Where(x => search_strs.Any(keyword => (x).Contains(keyword))).ToList();                                                                   
}

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.