【问题标题】:Filtering on multiple DataTables in a DataSet过滤数据集中的多个数据表
【发布时间】:2009-01-08 21:58:54
【问题描述】:

我有一个包含多个数据表的数据集。我想显示来自产品数据表的信息,它是数据集的中心表。但我希望能够根据周围表中的值过滤 DataSet。

例如,我想获取所有具有名为 Width 的功能 (DataTable) 和名为“Microsoft”的供应商 (DataTable) 的产品。

我可以将 DataTables 合并到一个 DataView 中,但这会导致 DataTables 之间的一对多关系出现问题。

【问题讨论】:

  • 你使用的是什么版本的框架?

标签: c# .net dataset


【解决方案1】:

这有点手动,但代码应该可以工作:

    // 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);

【讨论】:

    猜你喜欢
    • 2019-05-10
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多