greenSacrifice
greenSacrifice

Reputation: 93

Compare 2 dictionaries and return missing values

How would I compare these 2 dictionaries and return only the values missing?

The GetFileListFromBlob() function gets all file names and I'd like to know what is missing from the db.

Or is there a better way to get the missing values from these objects? Should I use different key/ value?

Dictionary<int, string> databaseFileList = new Dictionary<int, string>;
Dictionary<int, string> blobFileList = new Dictionary<int, string>;

int counter = 0;
foreach (string f in GetFileListFromDB())
{
    counter++;
    databaseFileList.Add(counter,  f );
}

counter = 0;
foreach (string f in GetFileListFromBlob())
{
    counter++;
    blobFileList.Add(counter, f);
}

// How to compare?

Thank you

Upvotes: 1

Views: 316

Answers (3)

LDS
LDS

Reputation: 362

private void CompareDictionary()
{
    var databaseFileList = new Dictionary<int, string>();
    var blobFileList = new Dictionary<int, string>();

    databaseFileList.Add(300, "apple");
    databaseFileList.Add(500, "windows");
    databaseFileList.Add(100, "Bill");

    blobFileList.Add(100, "Bill");
    blobFileList.Add(200, "Steve");

    var result = databaseFileList.Where(d2 => !blobFileList.Any(d1 => d1.Key == d2.Key)).ToList();
}

Upvotes: 0

sunside
sunside

Reputation: 8259

A HashSet<T> might be what you want (instead of a Dictionary<K,V>) - take this example:

var reference  = new HashSet<string> {"a", "b", "c", "d"};
var comparison = new HashSet<string> {"a",           "d", "e"};

When you now call ExceptWith on the reference set ...

reference.ExceptWith(comparison);

... the reference set will contain the elements "b" and "c" that do not exist in the comparison set. Note however that the extra element "e" is not captured (swap the sets to get "e" as the missing element) and that the operation modifies the reference set in-place. If that isn't wished for, the Except LINQ operator might be worth investigating, as was already mentioned in another answer.

Upvotes: 3

Mohammad Barbast
Mohammad Barbast

Reputation: 2049

The way I see it, you don't need counters at first (you can add them later).

You can use System.Collections.Generic.List<> type to go on.

List<int, string> databaseFileList = new List<string>(GetFileListFromDB());
List<int, string> blobFileList = new List<string>(GetFileListFromBlob());

//some code

Now if you want to get all items in both lists you can simply use Concat(...) method to unify them and then use Distinct() method to remove duplicate items:

List<string> allItems = databaseFileList.Concat(blobFileList).Distinct();

Now use Except(...) method to compare collections:

var missingItems1 = allItems .Except(databaseFileList);
//or
var missingItems1 = allItems .Except(blobFileList);
//or
//some other code

Upvotes: 0

Related Questions