C# Dictionaryの最初の要素を取得 |
やりたいことは、C#で辞書型の最初の値を取得したい。
Who's on Dictionary<>.First()?
http://stackoverflow.com/questions/436954/whos-on-dictionary-first
C#: get first key from Dictionary<string, string>
http://stackoverflow.com/questions/1820506/c-get-first-key-from-dictionarystring-string
ここらへんをみると、Firstが使えるって書いてあるので、こんなコードを書いてみる。
using System;
using System.Collections.Generic;
public class Sample {
public static void Main(string[] args) {
Dictionary<string, string> dic = new Dictionary<string, string>();
dic["テスト1"] = "テスト1の値";
dic["テスト2"] = "テスト2の値";
dic["テスト3"] = "テスト3の値";
KeyValuePair<string, string> pair = dic.First();
Console.WriteLine("First key: {0}, value {1}", pair.Key, pair.Value);
}
}
コンパイル時にこんなエラーが発生。
sample.cs(14,29): error CS1061: 'System.Collections.Generic.Dictionary<string,string>.KeyCollection' に 'First' の定義が含まれておらず、型 'System.Collections.Generic.Dictionary<string,string>.KeyCollection' の最初の引数を受け付ける拡張メソッドが見つかりませんでした。using ディレクティブまたはアセンブリ参照が不足しています。
ヒントはここ。
RSRP-179567 error CS1061: 'object' does not contain a definition for 'Foo' and no extension method 'Foo' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
http://youtrack.jetbrains.com/issue/RSRP-179567?query=p
using System.Linq;が必要でした。
using System;
using System.Collections.Generic;
using System.Linq;
public class Sample {
public static void Main(string[] args) {
Dictionary<string, string> dic = new Dictionary<string, string>();
dic["テスト1"] = "テスト1の値";
dic["テスト2"] = "テスト2の値";
dic["テスト3"] = "テスト3の値";
KeyValuePair<string, string> pair = dic.First();
Console.WriteLine("First key: {0}, value {1}", pair.Key, pair.Value);
}
}
これでコンパイルが通りました。
テキストエディタでコードを書いてる人特有で、普通は自動補完されるのだと思いますが、メモ書きとして。