Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Created July 20, 2013 13:10
Show Gist options
  • Select an option

  • Save ichiroku11/6044959 to your computer and use it in GitHub Desktop.

Select an option

Save ichiroku11/6044959 to your computer and use it in GitHub Desktop.
Func<TItem, TKey>を使ったKeyedCollection<TKey, TItem>の実装
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