Created
July 20, 2013 13:10
-
-
Save ichiroku11/6044959 to your computer and use it in GitHub Desktop.
Func<TItem, TKey>を使ったKeyedCollection<TKey, TItem>の実装
This file contains hidden or 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.Collections.ObjectModel; | |
| using System.Linq; | |
| using System.Text; | |
| using System.Threading.Tasks; | |
| namespace ConsoleApp { | |
| class DefaultKeyedCollection<TKey, TItem> : KeyedCollection<TKey, TItem> { | |
| private readonly Func<TItem, TKey> _func; | |
| public DefaultKeyedCollection(Func<TItem, TKey> func) { | |
| _func = func; | |
| } | |
| protected override TKey GetKeyForItem(TItem item) { | |
| return _func(item); | |
| } | |
| } | |
| class Product { | |
| public int Id { get; set; } | |
| public string Name { get; set; } | |
| } | |
| class Program { | |
| static void Main(string[] args) { | |
| var products = new DefaultKeyedCollection<int, Product>(product => product.Id) { | |
| new Product { Id = 1, Name = "Aaa" }, | |
| new Product { Id = 2, Name = "Bbb" }, | |
| new Product { Id = 3, Name = "Ccc" }, | |
| }; | |
| Console.WriteLine(products[1].Name); // Aaa | |
| Console.WriteLine(products[3].Name); // Ccc | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment