在两个字符串字典中查找字符串不相等的地方;林克

本文关键字:字符串 不相等 林克 查找 字典 两个 | 更新日期: 2023-09-27 18:15:40

我有两本字典

dicA从DB填充,dicB从Excel列填充。

dicA.Values可能等于dicB.Values,但大部分时间dicB.Values包含dicA.Values

问题:我想在dicB中找到包含dicA.Values的所有值,并将其添加到新字典dicNewdicNew.Key=dicA.keydicNew.Values=dicB.Values

我的解决方案我写了这个代码:

 Dictionary<string,string> res = new Dictionary<string, string>();
        foreach (var s in dicB)
        {
            var data = dicA.Where(x => x.Value.Contains(s.Value)).ToList();
                //check if data.count==1 add to autoBind
                //    autoBind.Add(data[0].Key,data[0].Value);
                // else find in data which value string has most equals
                // character then add this to Autobind 
        }

有没有其他方法(比我的代码更好(可以找到所有字典数据都可以匹配并将它们添加到autobind

编辑时间:CCD_ 13不等于CCD_ 14。我想找到如果dicA.valuedicB.values中,那么如果dicB.values.count==1添加到newDic中,则找到最佳匹配;哪个dicB.Values字符串具有最多相同的字符

在两个字符串字典中查找字符串不相等的地方;林克

var dictoinaryResult = dictionaryB.Where(x => dictionaryA.ContainsValue(x.Value)).ToDictionary(x=> x.Key, x=>x.Value);

使用此代码作为样本格式

Dictionary<int, string> abc = new Dictionary<int, string>();
            foreach (var a in dicA)
            {
                foreach (var b in dicB)
                {
                    if (a.key == b.key)
                    {
                        abc.add(Convert.ToInt32(a.key, b.value);
                    }
                }
            }
   Dictionary<int,string> dicta = new Dictionary<int, string>();
        Dictionary<int, string> dictb = new Dictionary<int, string>();
        dicta.Add(1, "Hi");
        dicta.Add(2, "Hello");
        dictb.Add(2, "Hiyo");
        dictb.Add(1, "Hllow");
        var list = (from d1 in dicta
                   let temp = dictb.FirstOrDefault(d2 => d2.Value.Contains(d1.Value))
                   where temp.Value != null
                   select new { d1.Key, temp.Value }).ToDictionary(d => d.Key ,d => d.Value );

我希望这会有所帮助。

这应该有效:

var dicNew = dicB.Where(b => !dicA.ContainsValue(b.Value)).ToDictionary(x => x.Key, x => x.Value);

您可以使用自己的IEqualityComparer 以优雅的方式完成

class ValueComparer<TKey, TValue> : IEqualityComparer<KeyValuePair<TKey, TValue>>
    {
        public bool Equals(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y)
        {
            return GetHashCode(x) == GetHashCode(y);
        }
        public int GetHashCode(KeyValuePair<TKey, TValue> obj)
        {
            return obj.Value.GetHashCode();
        }
    }

然后你可以简单地使用

var dictC = dictA.Intersect(dictB, new ValueComparer<string, string>())