Created
February 1, 2011 02:58
-
-
Save cz75hiro/805336 to your computer and use it in GitHub Desktop.
インデクサにデリゲート
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.ObjectModel; | |
using System.Linq; | |
namespace インデクサにデリゲート { | |
class Program { | |
static void Main(string[] args) { | |
SampleCollection sample = SampleCollection.My; | |
sample.Add(new Hoge() { ID = 1, Name = "A" }); | |
sample.Add(new Hoge() { ID = 2, Name = "B" }); | |
sample.Add(new Hoge() { ID = 3, Name = "C" }); | |
sample.Add(new Hoge() { ID = 4, Name = "D" }); | |
sample.Add(new Hoge() { ID = 5, Name = "E" }); | |
sample.Add(new Hoge() { ID = 6, Name = "F" }); | |
//sample.Add(new Hoge() { ID = 3, Name = "G" }); //エラー | |
var r1 = sample[x => x.ID == 2]; | |
Console.WriteLine("{0}:{1}", r1.ID, r1.Name); //2:B | |
var r2 = sample[x => x.Name == "F"]; | |
Console.WriteLine("{0}:{1}", r2.ID, r2.Name); //6:F | |
//var r3 = sample[x => x.ID == 100];//エラー | |
Console.Read(); | |
} | |
} | |
public class SampleCollection : KeyedCollection<int, Hoge> { | |
static SampleCollection _this; | |
private SampleCollection() { | |
} | |
~SampleCollection() { | |
if (_this != null) { | |
_this.Clear(); | |
_this = null; | |
}; | |
} | |
public static SampleCollection My { | |
get { | |
if (_this == null) _this = new SampleCollection(); | |
return _this; | |
} | |
} | |
public Hoge this[Func<Hoge, bool> predicate] { | |
get { return _this.First(predicate); } | |
} | |
protected override int GetKeyForItem(Hoge item) { | |
return item.ID; | |
} | |
} | |
public class Hoge { | |
public int ID { get; set; } | |
public string Name { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment