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.
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:
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 theIEnumerable<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:
Now lc contains all data for control binding, what you need to do is
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 ofListClass
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.