C# 分离/比较数据表记录:有更好的方法吗?

C# 分离/比较数据表记录:有更好的方法吗?,c#,datatable,C#,Datatable,我很难回答这个问题,因为很难用语言来表达我想做的事情,但在这个例子中,我有三个数据表,它们来自一个数据库。“人员”表、“组”表和“peopleInGroups”链接表 我有两个列表视图,一个用于显示特定组中的人的姓名,另一个用于显示不在该组中的人的姓名。使用datarelation,我可以从groupID中获取组内人员的记录,作为datarow[],并使用简单的foreach循环填充“组内人员”列表视图,但我很难找到填充“组外人员”列表视图的方法 我最终找到的解决方案是创建两个新的数据表,一个用

我很难回答这个问题,因为很难用语言来表达我想做的事情,但在这个例子中,我有三个数据表,它们来自一个数据库。“人员”表、“组”表和“peopleInGroups”链接表

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

我最终找到的解决方案是创建两个新的数据表,一个用于“组内”,另一个用于“不在组内”,并在适当的情况下从中填充/删除。然而,这个过程看起来很混乱,有点慢,我相信一定有更好的方法来达到同样的目的

方法中的代码(编辑一点以尝试使其更通用):


出于兴趣,为什么不让数据库帮你做这些繁重的工作呢?对于给定的组id,您可以使用从peopleInGroup到peopleInGroup的左联接查询,并使用peopleInGroup值不为NULL的记录来填充组中的人员列表框。在peopleInGroup列的查询结果中,不在该组中的人将由空记录表示。我希望答案是“因为我不知道怎么做”。我对这类事情有点陌生。我想一定有比这更好的方法,而你的解决方案可能就是它!因为您已经有了一个数据表,我想您知道如何从数据库中获取数据。看看联接是如何工作的。这里有一个很好的教程:但是网上还有很多
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() }));
        }
    }