我有项目,我想将它们添加到Dictionary而不使用Add方法(因为它消耗了多少行)。有没有办法将项目添加到词典中
new List<string>() { "P","J","K","L","M" };
或类似List中的AddRange方法。任何帮助都会得到高度的关注。
答案 0 :(得分:4)
引自here
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}}
};
答案 1 :(得分:2)
您可以轻松创建一个为您的字典执行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();
}
}
}
答案 2 :(得分:1)
就像
一样简单var dictionary = new Dictionary<int, string>() {{1, "firstString"},{2,"secondString"}};