Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

391
Views
Comparación de dos diccionarios (clave, valor) y devolución de claves que no tienen el mismo valor

Soy un poco nuevo en C# y quiero identificar claves que no tengan el mismo valor al comparar dos diccionarios.

El diccionario que tengo es de dict => KeyValuePair<string, string> . Y tengo dos diccionarios como -

 dict1 => {"a":"False","b":"amazonaws.com","c":"True"} dict2 => {"a":"True","b":"amazonaws.com","c":"False"}

Quiero comparar ambos diccionarios y devolver una variable que tendrá Claves ["a", "c"] como en el ejemplo anterior, esas claves tienen un valor diferente.

Actualmente, la lógica que he escrito solo diferenciará las claves que no están en el otro diccionario.

 Dictionary dictExcept = null; foreach (IDictionary kvp in dict1.Cast<object>().Where(kvp => !dict2.Contains(kvp))) { dictExcept.Add(kvp.Keys, kvp.Values); } return dictExcept ;
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Puedes intentar usar TryGetValue :

 using System.Linq; ... var dictExcept = dict1 .Where(pair => dict2.TryGetValue(pair.Key, out var value) && pair.Value != value) .ToDictionary(pair => pair.Key, pair => (first: pair.Value, second: dict2[pair.Key]));

Aquí, para cada pair de valores clave de dict1 intentamos obtener el value correspondiente de dict2 :

 // dict2 has pair.Key it corresponds to value... dict2.TryGetValue(pair.Key, out var value) && // however value from dict2 != value from dict1 pair.Value != value

La misma idea si prefiere usar foreach (sin solución Linq ):

 var dictExcept = new Dictionary<string, (string first, string second)>(); foreach (var pair in dict1) if (dict2.TryGetValue(pair.Key, out var value) && value != pair.Value) dictExcept.Add(pair.Key, (pair.Value, value));

Demostración: ( violín )

 var dict1 = new Dictionary<string, string> { { "a", "False" }, { "b", "False" }, { "c", "True" }, { "d", "dict1 only" } }; var dict2 = new Dictionary<string, string> { { "a", "False" }, { "b", "True" }, { "c", "False" }, { "e", "dict2 only" } }; var dictExcept = dict1 .Where(pair => dict2.TryGetValue(pair.Key, out var value) && pair.Value != value) .ToDictionary(pair => pair.Key, pair => (first: pair.Value, second: dict2[pair.Key])); string report = string.Join(Environment.NewLine, dictExcept .Select(pair => $"Key: {pair.Key}; Values: {pair.Value}")); Console.Write(report);

Salir:

 Key: b; Values: (False, True) Key: c; Values: (True, False)
over 4 years ago · Santiago Trujillo Report

0

Dado que tiene un diccionario llamado dictExcept , ¿qué le parece usar Expect para que haga el trabajo por usted?

Produce la diferencia de conjunto de dos secuencias.

fuente

Y en tu caso:

 using System; using System.Collections.Generic; using System.Linq; public class Program { static void Main(string[] args) { var a = new Dictionary<string, string>{{"a", "False"}, {"b", "False"}, {"c", "True"}}; var b = new Dictionary<string, string>{{"a", "False"}, {"b", "True"}, {"c", "False"}}; var c = a.Except(b).Select(x => x.Key); c.Dump(); } }

producción

 [ b, c ]

¡Pruébelo en línea!

Más ejemplos con diferentes casos:

 static void Main(string[] args) { var a = new Dictionary<string, string>{{"a", "False"}, {"b", "False"}, {"c", "True"}}; var b = new Dictionary<string, string>{{"a", "False"}, {"b", "True"}, {"c", "False"}}; var c = a.Except(b).Select(x => x.Key); // c is [ b ,c ] a.Add("d", "foo"); var d = a.Except(b).Select(x => x.Key); // d is [ b, c, d ] b.Add("e", "foo"); var e = a.Except(b).Select(x => x.Key); // e is still [ b, c, d ] var e2 = (a.Except(b)).Union(b.Except(a)).Select(x => x.Key).Distinct(); // e is [ b, c, d, e ] }

¡Pruébelo en línea!

over 4 years ago · Santiago Trujillo Report

0

Proporcionando la respuesta más simple debido a su comentario:

Ambos diccionarios tendrán las mismas claves, solo que necesitamos identificar las claves que tienen diferentes valores

Trabajando bajo la suposición de que no necesita tener en cuenta las claves que faltan, simplemente puede iterar sobre todas las claves de uno de los diccionarios y comparar los valores encontrados debajo de esa clave.

 var keysWithDifferentValues = new List<string>(); foreach (var kvp in dict1) { if(!kvp.Value.Equals(dict2[kvp.Key])) keysWithDifferentValues.Add(kvp.Key); }

Esto se puede simplificar usando LINQ:

 var keysWithDifferentValues = dict1 .Where(kvp => !kvp.Value.Equals(dict2[kvp.Key])) .Select(kvp => kvp.Key) .ToList();
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!