c# - 字典C#中的数组

字典(键,值)就像:


[A, green]


[B, blue]


[C, yellow]


[D, green]


[E, blue]



和数组:

[A,B,A,C,B,D,E]

我希望得到以下结果:

[green,blue,green,yellow,blue,green,blue]

时间:

可以使用LINQ实现,如下所示


var result = yourArray.Select(item => yourDictionary[item]).ToArray();



使用Dictionary .Values


 using System.Linq;



 Dictionary<string, string> dic = new Dictionary<string, string>()


 {


 {"A" ,"GREEN" },


 {"B" ,"BLUE"}


 };



 string[] ary;


 ary = dic.Values.ToArray();




 foreach (string color in dic.Values)


 {


 //...


 }



你可以尝试linq


using System.Linq;



...



var result = array


 .Select(item => dictionary[item])


 .ToArray();



或者旧的for循环:


//TODO: put the right type instead of Color


Color[] result = new Color[array.Length];



for (int i = 0; i < result.Length; ++i)


 result[i] = dictionary[array[i]];



...