首页 > 解决方案 > 如何正确合并字典?

问题描述

我有这样的字典

            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)

如何解决?

标签: c#

解决方案


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();
}

推荐阅读