c# - 过滤数据集中的多个数据表

标签 c# .net dataset

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

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

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

最佳答案

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

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

关于c# - 过滤数据集中的多个数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/426179/

相关文章:

c# - 非常简单的代码中类、结构或接口(interface)成员声明中的无效标记 'while'

C# 包装器类和来自 C++ 的 dllimport

c# - CustomValidator 验证多个控件

java - 使用 Java 存储和检索大型数据集的最佳方式

python - 在 TensorFlow 2.0 中,如何查看数据集中的元素数量?

c# - 当 XML 文件包含法语数据时无法将 XML 文件读入数据集

c# - 在 .net 中删除继承的属性

c# - 使用 Case/Switch 和 GetType 来确定对象

C# 能力?

c# - 使将 CSV 字符串导入到类的列表中更容易