【问题标题】:Combining Two Lists Based on first 6 Characters根据前 6 个字符组合两个列表
【发布时间】:2018-09-06 04:04:41
【问题描述】:

我有两个列表(当前列表和新列表)。 Current 可以包含 100,000 多个字符串,每个字符串都以唯一的数字开头。 New 可以包含 50 到 200 个字符串,每个字符串都有一个唯一的编号。

如果 New 包含以相同 6 个字符开头的字符串,则它应该替换 Current 中的相同条目。任何不存在于 Current 中但存在于 New 中的新条目都应添加到 Current。我考虑过 Union、Concat 和 Intersect,但每个都只处理整个字符串。

有没有办法只比较列表中项目的前 6 个字符,如果发现它存在于 New 中,则替换 Current 中的条目?

也许将上述可视化的最简单方法是:

当前

123456 66 Park Avenue Sydney

123456 88 River Road Sydney

Current 中的结果需要是

123456 88 Park Avenue Sydney

如果Current.Union(New, first X characters) 是可能的,那就完美了。

任何关于根据前 6 个字符合并两个列表而不重复的建议将不胜感激。

【问题讨论】:

  • 您当前的集合应该是前六个和完整字符串的Dictionary<string,string>。然后迭代 New,检查它的长度是否为 6 或更大,并获取前 6 个的子字符串。如果字典有键(前六个),用完整的字符串更新它。如果没有,则将子字符串添加为键,将完整的字符串添加为值。如果字符串的长度小于 6,则按照业务规则的规定进行。
  • 如果你能提供一个minimal reproducible example 带有示例输入和预期结果,那就太棒了。
  • 嗯,结果不应该是“123456 88 River Road Sydney”吗?

标签: c# list character union


【解决方案1】:

string.StartsWith 是你要找的。​​p>

【讨论】:

    【解决方案2】:

    应该这样做。注意我使用了两本字典,因为可能有重复的要替换,如果没有,你可以使用一个。

    public static void Coder42(List<string> current, IEnumerable<string> news)
    {
        Dictionary<string, string> newDict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        Dictionary<string, string> unfound = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    
        foreach (var n in news)
        {
            if (n.Length < 6) throw new Exception("Too short");
            var ss = n.Substring(0, 6);
            if (newDict.ContainsKey(ss)) throw new Exception("Can't be too new.");
            newDict[ss] = n;
            unfound[ss] = n;
        }
    
    
    
        for (int i = 0; i < current.Count; i++)
        {
            var s = current[i];
            if (s.Length >= 6)
            {
                var ss = s.Substring(0, 6);
                if (newDict.TryGetValue(ss, out string replacement))
                {
                    current[i] = replacement;
                    unfound.Remove(ss);
                }
            }
        }
    
        foreach(var pair in unfound)
            current.Add(pair.Value);
    }
    

    并使用测试:

    var current = new List<string>();
    current.Add("123456 a");
    current.Add("123457 b");
    current.Add("123458 c");
    
    var news = new List<string>();
    news.Add("123457 q");
    news.Add("123456 p");
    news.Add("123459 z");
    
    Coder42(current, news);
    
    foreach (var s in current) Console.WriteLine(s);
    Console.ReadLine();
    

    给予:

    123456 p
    123457 q
    123458 c
    123459 z
    

    【讨论】:

    • 优秀。我在 2000 条记录和 20 条记录上试用了它,并对它的表现印象深刻。稍后将在 100,000 上试用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 2013-06-07
    • 2013-09-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多