Doing a multi-column search for an item in a listView control using c#

756 views Asked by At

I am using a multi-column listView control in Visual Studio 2013 and coding with C#. I want to do a search on multiple columns as if I were doing a database SELECT. For example, if the first three columns were NAME, AGE and CITY, I might want to search for an Item where NAME = "Fred", AGE >= 20 and CITY = "Chicago" and then select that Item.

  • What is the most efficient way to do this?
  • Can linq be used?
  • Is there another way short of traversing the entire collection of Items and testing each column value? Appreciate any assistance.
2

There are 2 answers

9
Mrinal Kamboj On BEST ANSWER

Yes, it can be done, you are using the multi-column listView control, which i assume would have a data source like datatable. Which would contains Columns / Rows which would be rendered in the control.

You can easily use Linq to achieve the result, something like:

dataTable.AsEnumerable
         .Where(x=>x["NAME"] == "Fred")
         .Where(x=>x["AGE"] >= 20)
         .Where(x=>x["CITY"] == "Chicago")

Here each x represents a Row, since you are enumeration a Row Collection of a DataTable. Final result will be of Type IEnumerable<DataRow>, which you need to use to create separate DataTable than can be bind to the control, I am not sure if you can bind the IEnumerable<DataRow>.

Also check the following links:

Linq : select value in a datatable column

LINQ query on a DataTable

Adding more details to help OP further, the class available is List, that you are binding to the control, this makes life even easier, since, it is an IEnumerable type, what you need to do it use this class in the Linq query above as follows:

IList<ListClass> lc = new List<ListClass>();

Now lc contains all data for control binding, what you need to do is

var Result = lc
             .Where(x=>x.Name == "Fred")
             .Where(x=>x.Age >= 20)
             .Where(x=>x.City == "Chicago").ToList();

Here Result will be of type List<ListClass>, which contains the filtered records, as per your requirement, which can be used for binding with the control.

Here x would be an object of ListClass in the Linq query, similarly you can dynamically supply values to the Linq query and keep getting the filtered subset. All the properties will be available in intellisense since we have strongly typed object. Hope this helps in further clarifying.

1
ycsun On

The type of ListView.Items is ListView.ListViewItemCollection, which implements IEnumerable, so surely LINQ can be used. You can do something like the following:

theListView.Items.Where(item =>
    item.Text == "Fred" &&
    Int32.Parse(item.SubItems[0].Text) >= 20 &&
    item.SubItems[1].Text == "Chicago")