Created
February 6, 2018 09:17
-
-
Save anonymous/7b42e850a22bcea55883845e127be0b8 to your computer and use it in GitHub Desktop.
IDictionary of enumerables vs ILookup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace ConsoleApp3 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Arrange | |
Dictionary<string, IEnumerable<string>> dictionary = new Dictionary<string, IEnumerable<string>> | |
{ | |
{"first", new[] {"a", "b", "c"}}, | |
{"second", new[] {"a", "b", "c"}}, | |
{"third", new[] {"b"}} | |
}; | |
ILookup<string, string> lookup = (from kvp in dictionary | |
from value in kvp.Value | |
select new { kvp.Key, value }) | |
.ToLookup(_ => _.Key, _ => _.value); | |
// at this point dictionary and lookup are equivalent | |
// filter dictionary | |
var filteredDictionary = (from kvp in dictionary | |
select new | |
{ | |
kvp.Key, | |
values = | |
from value in kvp.Value | |
where value != "b" | |
select value | |
}) | |
.ToDictionary(_ => _.Key, _ => _.values); | |
// we now have dictionary without "b"-s but all keys are preserved | |
foreach (var keyValuePair in filteredDictionary) | |
{ | |
Console.WriteLine($"{keyValuePair.Key} holds {keyValuePair.Value.Count()} entries"); | |
} | |
// filter lookup | |
Console.WriteLine("-------------------------------------------"); | |
var filteredLookup = (from grouping in lookup | |
from value in grouping | |
where value != "b" | |
select new { grouping.Key, value }) | |
.ToLookup(_ => _.Key, _ => _.value); | |
// we now have lookup without "b"-s but keys are NOT preserved (empty ones ommited) | |
// so we lost third key altogether | |
foreach (var grouping in filteredLookup) | |
{ | |
Console.WriteLine($"{grouping.Key} holds {grouping.Count()} entries"); | |
} | |
Console.ReadKey(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment