简体   繁体   中英

c# searching arraylist

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.

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#

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM