0

I am making a simple app that reads data in from a file. So far i have been able to read in all the data into an arraylist.

However i need to give the user the ability to search the arraylist and return all the values associated with their search. To search the user enters a keyword or what ever into a text box and when they click search the related results will appear in a list box.

What code do i need to be able to search an arraylist.

6
  • 1
    What type of data do you store in the ArrayList? Commented Mar 23, 2011 at 8:45
  • Why ArrayList? Are you still using .net 1? Commented Mar 23, 2011 at 8:45
  • ArrayList is old-school .Net 1.0 stuff. We're on .Net 4 now. You may want to use a List<string> instead. Commented Mar 23, 2011 at 8:46
  • @Adrian Faciu in the arraylist i am storing strings for example like the customer number customer name etc. Commented Mar 23, 2011 at 8:47
  • @user667430: maybe you could accept some answers to your previous questions... Commented Mar 23, 2011 at 8:49

2 Answers 2

5

Perhaps you want to do something like this:

Loading the file into a List<string>:

List<string> lines=File.ReadAllLines(filename);

Searching in the List<string>:

IEnumerable<string> foundLine=lines.Where(s=>s.Contains(searchString));
foreach(string foundLine in lines)
  listBox1.Items.Add(foundLine);

Note that string.Contains uses ordinal comparison(case sensitive, culture invariant), that might not be what you want. And it doesn't deal with non normalized unicode sequences either.

You could use the following extension method to support other comparision modes:

public static bool Contains(this string str, string value, StringComparison comparisonType)
{
  return str.IndexOf(value, comparisonType) >= 0;
}

https://connect.microsoft.com/VisualStudio/feedback/details/435324/the-string-contains-method-should-include-a-signature-accepting-a-systen-stringcomparison-value#

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

Comments

2

You can use:

string searchString = txtSearch.Text.Trim();
ArrayList arrayResult = new ArrayList();
foreach(object obj in arrayList)
{
   if(searchString == Convert.ToString(obj))
   {
      arrayResult.Add(obj);
   }

}
ListBox.DataSource = arrayResult;

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.