Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
2 dictionary collections
Message
De
29/09/2016 09:30:19
 
 
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Versions des environnements
Environment:
C# 5.0
OS:
Windows 10
Database:
MS SQL Server
Divers
Thread ID:
01641447
Message ID:
01641497
Vues:
35
>>>Hi everybody,
>>>
>>>How can I get difference between these two Dictionaries using except operator? I'm trying this code but it doesn't compile
>>>
>>>
>>>prefsRetailViewModel.AvailableTrackingColumns = this.trackingLookupOrderColumns.Except(prefsRetailViewModel.AssignedTrackingColumns);
>>>
>>>All of them are defined as
>>>
>>>Dictionary<string, string>
>>>
>>>Thanks a lot in advance.
>>
>>If you want to use Except you could implement IEqualityComparer:
public class StringDictionaryComparer : IEqualityComparer<KeyValuePair<string,string>>
>>        {
>>            public bool Equals (KeyValuePair<string, string> a , KeyValuePair<string, string> b)
>>            {
>>                return a.Key == b.Key;
>>            }
>>
>>            public int GetHashCode(KeyValuePair<string, string> item)
>>            {
>>                return item.GetHashCode();
>>            }
>>        }
Your code should then work (assuming you only need to check the key)
>
>How the code should look like after I added this class?
>
>I added it inside the APIController file (beneath the class).

Actually my idea was overkill. Since your key value is a string then the default comparer should work anyway. What was the problem with your original code? Simple working example:
static void Main(string[] args)
        {
            Dictionary<string, string> AssignedTrackingColumns = new Dictionary<string,string>();
            Dictionary<string, string> TrackingLookupOrderColumns = new Dictionary<string, string>();

            TrackingLookupOrderColumns.Add("A", "One");
            TrackingLookupOrderColumns.Add("B", "Two");
            TrackingLookupOrderColumns.Add("C", "Three");
            TrackingLookupOrderColumns.Add("D", "Four");

            AssignedTrackingColumns.Add("A", "One");
            AssignedTrackingColumns.Add("C", "Three");

            var result = TrackingLookupOrderColumns.Except(AssignedTrackingColumns);

            foreach (var x in result)
            {
                Console.WriteLine(string.Format("Key:{0} Value:{1}",x.Key,x.Value));
            }
            Console.ReadLine();
        }
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform