分离/比较DataTable记录:有更好的方法吗?

时间:2011-12-02 21:59:23

标签: c# datatable

因为很难说出我正在尝试做的事情,因此很难解决这个问题,但在这个例子中,我有三个从数据库中获取的数据表。 “人员”表,“组”表和“peopleInGroups”链接表。

我有两个listView,一个用于显示特定组中人员的姓名,另一个用于显示不在该组中的人员。使用datarelation我可以从groupID获取组中人员的记录作为datarow []并使用简单的foreach循环填充“group in group”listView,但是我很难找到填充“people”的方法不在小组“listView。

我最终得出的解决方案是创建两个新数据表,一个用于“在组中”,一个用于“不在组中”,并在适当时填充/删除它们。然而,这个过程似乎很混乱,而且有点慢,我相信必须有更好的方法来达到同样的目的。

该方法的代码(编辑了一下以使其更通用):

private void PopulateListBoxes(string comboBoxGroupName)
    {
        // create copies of the "people" DataTable, one empty one full
        DataTable dtPeopleNotInGroup = myDataSet.Tables["people"].Copy();
        DataTable dtPeopleInGroup = myDataSet.Tables["people"].Clone();
        DataView dvPeopleNotInGroup = new DataView(dtPeopleNotInGroup, "", "PersonID", DataViewRowState.CurrentRows);
        DataView dvPeopleInGroup = new DataView(dtPeopleInGroup);

        // find the specific group row from the groups table using a specific groupID
        string stm = "groupid = somegroupid"
        DataRow[] drGroupID = dsMainDB.Tables["groups"].Select(stm);

        foreach (DataRow groupIDRow in drGroupID)
        {
            foreach (DataRow peopleInGroupRow in groupIDRow.GetParentRows(myDataSet.Relations["relPersonID"]))
            {
                // delete this row from the full datatable
                int removeThisPerson = dvPeopleNotInGroup.Find(peopleInGroupRow["PersonID"]);
                dvPeopleNotInGroup.Delete(removeThisPerson);

                // add this row to the empty data table
                dtPeopleInGroup.ImportRow(peopleInGroupRow);
            }
        }

        dvPeopleNotInGroup.Sort = "lastname";
        dvPeopleInGroup.Sort = "lastname";

        // populate the "In group" listView from the data view
        foreach (DataRowView inGroupRowView in dvPeopleInGroup)
        {
            listViewPeopleInGroup.Items.Add(new ListViewItem(new string[] { inGroupRowView["PersonID"].ToString(),
               inGroupRowView["FirstName"].ToString() + " " + inGroupRowView["LastName"].ToString() }));
        }

        // populate the "Not in group" listView from the data view
        foreach (DataRowView notInGroupRowView in dvPeopleNotInGroup)
        {
            listViewPeopleNotInGroup.Items.Add(new ListViewItem(new string[] { notInGroupRowView["PersonID"].ToString(),
               notInGroupRowView["FirstName"].ToString() + " " + notInGroupRowView["LastName"].ToString() }));
        }
    }

0 个答案:

没有答案