tags:

views:

807

answers:

2

I have a DataSet containing multiple DataTables. I want to display information from the Product DataTable, which is the center table of the DataSet. But I want to be able to filter the DataSet on values from the surrounding tables.

For example, I want to get all the Products that have a Feature (DataTable) named Width and have a Supplier (DataTable) named “Microsoft”.

I could merge the DataTables to one DataView but that causes a problem with the one-to-many relationships between the DataTables.

A: 

What does your data structure look like?

BobTheBuilder
+1  A: 

This is a bit manual but the code should work:

    // Helper Functions
    private static List<T> RemoveDuplicates<T>(List<T> listWithDuplicates)
    {
        List<T> list = new List<T>();
        foreach (T row in listWithDuplicates)
        {
            if(!list.Contains(row))
                list.Add(row);
        }
        return list;
    }

    private static List<DataRow> MatchingParents(DataTable table, string filter, string parentRelation)
    {
        List<DataRow> list = new List<DataRow>();
        DataView filteredView = new DataView(table);
        filteredView.RowFilter = filter;
        foreach (DataRow row in filteredView.Table.Rows)
        {
            list.Add(row.GetParentRow(parentRelation));
        }
        return list;
    }

    // Filtering Code
    List<DataRow> productRowsMatchingFeature = MatchingParents(productDS.Feature, 
                                                                   "Name = 'Width'",
                                                                   "FK_Product_Feature");

    List<DataRow> productRowsWithMatchingSupplier = MatchingParents(productDS.Supplier,
                                                                   "Name = 'Microsoft'",
                                                                   "FK_Product_Supplier");

    List<DataRow> matchesBoth = productRowsMatchingFeature.FindAll(productRowsWithMatchingSupplier.
                                                                           Contains);

    List<DataRow> matchingProducts = RemoveDuplicates(matchesBoth);
Brownie
I quite like this +1
cgreeno