c# - 如何正确合并字典?
问题描述
我有这样的字典
Dictionary<string, HashSet<string>> source = new Dictionary<string, HashSet<string>>()
{
{"1", new HashSet<string>() { "test1 (Uploaded)", "test2", "test3 (Uploaded)"}},
{"2", new HashSet<string>() { "test1 (Uploaded)", "test2", "test3"}},
{"3", new HashSet<string>() { "test1 (Uploaded)", "test2", "test3 (Uploaded)"}},
};
我需要合并它以便只获得List<string>
唯一值,但还有一个条件。例如,如果我有第一项"test3 (Uploaded)"
和第二项,"test3"
我需要在最终列表中添加test3
值。最终结果我应该得到这个
test1 (Uploaded)
test2
test3
为了做到这一点,我写了这样的方法
private static List<string> MergingFilter(Dictionary<string, HashSet<string>> inVal)
{
List<string> result = new List<string>();
foreach (var pair in inVal)
{
HashSet<string> agentContent = pair.Value;
foreach (string file in agentContent)
{
bool isShouldBeAdded = true;
for (int i = 0; i < result.Count; i++)
{
string tmpResultFile = result[i];
if (tmpResultFile.Contains(file)
&& tmpResultFile.Contains("(Uploaded)")
&& !file.Contains("(Uploaded)"))
{
isShouldBeAdded = false;
result[i] = file;
break;
}
else if (tmpResultFile == file)
{
isShouldBeAdded = false;
break;
}
}
if (isShouldBeAdded)
{
result.Add(file);
}
}
}
return result;
}
但它给了我结果
test1 (Uploaded)
test2
test3
test3 (Uploaded)
如何解决?
解决方案
private static List<string> MergingFilter(Dictionary<string, HashSet<string>> inVal) {
HashSet<string> combined = new HashSet<string>();
// loop through inVal.Values and add the hashsets into combined
foreach (HashSet<string> hashset in inVal.Values) {
combined.UnionWith(hashset);
}
// remove any duplicate inside combined like "test3" and "test3 (Uploaded)"
foreach (string item in combined.ToArray() /* acts as some kind of copy */) {
if (item.EndsWith(" (Uploaded)") && combined.Contains(item[0..^11])) {
combined.Remove(item);
}
}
return combined.ToList();
}
推荐阅读
- java - 位图在某些 android 设备上无法保存到图库
- r - 用高于和低于平均值的 SD 值替换异常值
- javascript - 如何编辑 Material UI DataGrid 中的特定行?
- javascript - JavaScript:试图找到一种方法来调整窗口大小时如何刷新我的 div.offsetTop 值
- apigee - 如何在 APIGEE 中公开通过后端服务器上的 API 密钥进行身份验证的后端 API?
- c# - 缺少 Microsoft.Practice.ObjectBuilder2.dll
- windows - 如何在 Windows 上安装 apache kafka?安装错误?
- python - 嗨,我试图用python编写这段代码,但我有一个错误,我希望有人能帮助我
- c# - 从接口为 InterfaceA 的 Unity 容器中获取对象
其中 InterfaceB 是可变的 - griddb - GridDB 连接超时