我正在学习编程,我的问题是我有一堆对象,我想只有在列表尚未包含该对象时才将这些对象添加到列表中.其次,如果对象已经包含,我想忽略该对象并添加下一个对象.我想我的第一部分工作只需要第二部分的帮助.非常感谢.
PartyGroup partyGroup = new PartyGroup();
using (AseDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (!myPartyGroupList.Contains(partyGroup))
{
partyGroup.PartyGroupID = Convert.ToInt32(reader["party_group_id"]);
partyGroup.PartyGroupName = reader["party_group_name"].ToString();
partyGroup.PersonList = myPersonList;
myPartyGroupList.Add(partyGroup);
}
else
{
//??
}
}
}
Run Code Online (Sandbox Code Playgroud)
你已经完成了第一部分.
只需删除'else'子句,您的例程将自动在下一次迭代中添加下一个元素.像这样:
while (reader.Read())
{
if (!myPartyGroupList.Contains(partyGroup))
{
partyGroup.PartyGroupID = Convert.ToInt32(reader["party_group_id"]);
partyGroup.PartyGroupName = reader["party_group_name"].ToString();
partyGroup.PersonList = myPersonList;
myPartyGroupList.Add(partyGroup);
}
}
Run Code Online (Sandbox Code Playgroud)
比较时,最好使用标识符进行比较,在您的例子中是 PartyGroupId。如果您使用 contains,则使用 Contains() 的默认重载,然后使用列表中对象的哈希值进行比较。
因此,您可以创建自定义 IEqualityComparer 实现或使用 Linq 的Where 子句,而不是将比较留给 .NET,如下所示。
using (AseDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int groupId = Convert.ToInt32(reader["party_group_id"]);
if (partyGroupsList.Where(partyGroup => partyGroup.PartyGroupID == groupId).Any() == false)
{
PartyGroup newPartyGroup = new PartyGroup()
{
PartyGroupID = groupId,
PartyGroupName = reader["party_group_name"].ToString(),
PersonList = myPersonList
};
partyGroupsList.Add(newPartyGroup);
}
// If object already exists in the list then do not add, continue
// to the next row.
}
}
Run Code Online (Sandbox Code Playgroud)
另一个建议是将 PartyGroup 类成员重命名为:
class PartyGroup
{
public int ID { get; set; }
public string Name { get; set; }
public IList PersonList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)