項目があり、Add メソッドを使用せずに Dictionary に追加したい (行数を消費するため)。次のような項目を Dictionary に追加する方法はありますか
new List<string>() { "P","J","K","L","M" };
またはリストの AddRange メソッドのように。どんな助けでも非常に高く評価されます。
項目があり、Add メソッドを使用せずに Dictionary に追加したい (行数を消費するため)。次のような項目を Dictionary に追加する方法はありますか
new List<string>() { "P","J","K","L","M" };
またはリストの AddRange メソッドのように。どんな助けでも非常に高く評価されます。
ここから引用
Dictionary<int, StudentName> students = new Dictionary<int, StudentName>()
{
{ 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
{ 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317}},
{ 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198}}
};
辞書の AddRange を実行する拡張メソッドを簡単に作成できます
namespace System.Collections.Generic
{
public static class DicExt
{
public static void AddRange<K, V>(this Dictionary<K, V> dic, IEnumerable<K> keys, V v)
{
foreach (var k in keys)
dic[k] = v;
}
}
}
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var list = new List<string>() { "P", "J", "K", "L", "M" };
var dic = new Dictionary<string, bool>();
dic.AddRange(list, true);
Console.Read();
}
}
}
それは簡単です
var dictionary = new Dictionary<int, string>() {{1, "firstString"},{2,"secondString"}};