我在 DataSet
中有两个 DataTables
通过 DataRelation
链接在一起,我试图选择所有有子行的父行值为 x 的行。
父表包含产品,子表包含产品所属的类别。
DataSet dsProducts = new DataSet();
DataTable dtProducts = new DataTable("products");
dtProducts.Columns.Add("entity_id", typeof(int));
dtProducts.Columns.Add("sku", typeof(string));
dtProducts.Columns.Add("mpn", typeof(string));
dtProducts.Columns.Add("brand", typeof(string));
dtProducts.Columns.Add("name", typeof(string));
dtProducts.Columns.Add("description", typeof(string));
dtProducts.Columns.Add("short_description", typeof(string));
dtProducts.Columns.Add("image", typeof(string));
dtProducts.Columns.Add("weight", typeof(double));
dtProducts.Columns.Add("qty", typeof(double));
dtProducts.Columns.Add("cost", typeof(double));
dtProducts.Columns.Add("price", typeof(double));
dtProducts.PrimaryKey = new DataColumn[] { dtProducts.Columns["entity_id"] };
dsProducts.Tables.Add(dtProducts);
DataTable dtCategories = new DataTable("categories");
dtCategories.Columns.Add("entity_id", typeof(int));
dtCategories.Columns.Add("category_id", typeof(int));
dsProducts.Tables.Add(dtCategories);
dsProducts.Relations.Add(new DataRelation("entity_id", dtProducts.Columns["entity_id"], dtCategories.Columns["entity_id"]));
编辑
我拼凑了这段 Linq 代码,它可以工作,但似乎没有 DataRelation
var rows = from prods in dsProducts.Tables["products"].AsEnumerable()
join cats in dsProducts.Tables["categories"].AsEnumerable() on prods.Field<int>("entity_id") equals cats.Field<int>("entity_id")
where cats.Field<int>("category_id") == id
select prods;
最佳答案
尝试:
DataRow[] rows = dsProducts.Tables["products"].Select("entity_id=" + id);
代替:
DataRow[] rows = dsProducts.Tables["products"].Select("Child(entity_id).category_id = " + id);
因为您已经在具有共同列“entity_id”的两个表之间创建了关系,所以只要匹配了您的entity_id,您就会得到想要的结果。
关于c# - DataSet 选择子行包含 x 值的父行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8884388/