Last active
July 24, 2018 13:15
-
-
Save joaopgrassi/63306e1e6563924b6d4eb1e00ec85c0c to your computer and use it in GitHub Desktop.
Playing around with SelectMany and Lookup(TKey, TElement). This example shows a List of Marvel Super Heroes and in which Universes they appear. The initial collection is composed by Universes that contains characters. The objective is to find out in which universes a character appeared.
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
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("List of Marvel universes where some famous super heroes appear"); | |
var universes = new[] | |
{ | |
new Universe("Earth-616", "Main Continuity", new[] | |
{ | |
new Character(1, "Captain America"), | |
new Character(2, "Spider Man"), | |
new Character(3, "Thor"), | |
}), | |
new Universe("Earth-1610", "Ultimate Marvel", new[] | |
{ | |
new Character(2, "Spider Man"), | |
new Character(3, "Thor") | |
}), | |
new Universe("Earth-1298", "Mutant X", new[] | |
{ | |
new Character(3, "Thor"), | |
}), | |
}; | |
var charactersUniverse = (from helper in universes | |
.SelectMany(l => l.Characters, (universe, character) => new { universe, character }) | |
select new { UniverseId = helper.universe.Id, Character = helper.character }) | |
.ToLookup(c => c.Character.Id, c => c.UniverseId); | |
foreach (var character in charactersUniverse) | |
{ | |
var worlds = string.Join(", ", character.ToList()); | |
Console.WriteLine($"Character: {character.Key} seen in these universes: [{worlds}]"); | |
} | |
Console.ReadLine(); | |
} | |
} | |
public class Universe | |
{ | |
public string Id { get; set; } | |
public string Name { get; set; } | |
public IEnumerable<Character> Characters { get; set; } | |
public Universe(string id, string name, IEnumerable<Character> characters) | |
{ | |
Id = id; | |
Name = name; | |
Characters = characters; | |
} | |
} | |
public class Character | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
public Character(int id, string name) | |
{ | |
Id = id; | |
Name = name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment