Memfilter beberapa DataTables dalam DataSet

Saya memiliki DataSet yang berisi beberapa DataTables. Saya ingin menampilkan informasi dari Product DataTable, yang merupakan tabel tengah DataSet. Tapi saya ingin bisa memfilter DataSet berdasarkan nilai dari tabel di sekitarnya.

Misalnya, saya ingin mendapatkan semua Produk yang memiliki Fitur (DataTable) bernama Lebar dan memiliki Pemasok (DataTable) bernama “Microsoft”.

Saya dapat menggabungkan DataTables menjadi satu DataView tetapi hal itu menyebabkan masalah dengan hubungan satu-ke-banyak antara DataTables.


person Remco Eissing    schedule 08.01.2009    source sumber
comment
Versi kerangka apa yang Anda gunakan?   -  person cgreeno    schedule 09.01.2009


Jawaban (1)


Ini sedikit manual tetapi kodenya akan berfungsi:

    // 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);
person Brownie    schedule 09.01.2009