How do you search through a datatable?

glasswizzard

Well-known member
Joined
Nov 22, 2019
Messages
126
Programming Experience
Beginner
Could someone give me a rundown on how to search through a datatable looking for matching data please. I made this image of a simple table:

NumberGridExample.png


I forgot to add column headers but lets say the headers are the letters A, B, C, and D. When I execute the search I want the numbers to be examined and any that are the same are to be reported like "AA matches AD and DA with 4. AB matches ED with 9. AC matches CA and DB with 5" etc

The number of columns will never change but the rows will increase over time. I'm only asking about how to implement the search functionality, not about showing the results or anything else (the other stuff may pop up in it's own thread at some point), I just want this thread to be laser focused on that one aspect of this.

Thanks
 
If your data is in a DataTable, presumably the data came from a database. You should really let the database do the searching for you because that is what databases are built for: fast queries/searches.

But if you really must search a DataTable there is always the brute force approach. Here's the pseudo-code:
C#:
var columns = table.Columns;
foreach(var row in table.Rows)
{
    foreach(var column in columns)
    {
        var value = row[column.ColumnName]
        if (value is the item you are looking for)
            Do something with the found item
    }
}
 
Thanks for the psuedocode Skydiver, it's really helpful.

If your data is in a DataTable, presumably the data came from a database. You should really let the database do the searching for you because that is what databases are built for: fast queries/searches.

The DataTable is the data source for a datagrid on my UI, that's why I'm using a DataTable, I'm not using a database. Maybe I'm using the wrong thing for the wrong reason?
 
If you've gone down the WPF path, most people ditch DataSet's and DataTable's and simply use Lists, ObservableCollections, anything else that exposes IEnumerable.
 

Latest posts

Back
Top Bottom