我有两个长度相同的数组,我需要将第一个用作Key
,第二个用作Value
。
我的Key
是唯一的string
,我的Value
是双倍的。
我有6个水豚。他们的名字将成为关键,他们的重量就是英镑。
我目前的代码:
ViewBag.MeuBalaioDeCapivaras = new string[]
{
"Jerimúndia",
"Genoveva",
"Facibulana",
"Carnavala",
"Dentinhos Dourados",
"Creusa"
};
ViewBag.PesoDeCadaCapivaraDoMeuBalaioDeCapivaras = new double[]
{
500.0,
400.0,
250.0,
12.0,
1589.0,
87.3
};
这是我的阵列,我正在做KeyValuePair
:
var keyValuePair = new KeyValuePair<string, double>(ViewBag.NomeDaCapivara, ViewBag.PesoDeCadaCapivaraDoMeuBalaioDeCapivaras);
它编译得很完美,但最终它在运行时给了我一个例外:
=> An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code. Additional information: The best correspondence of the overloaded method.
我怎样才能做我需要的事?
答案 0 :(得分:8)
LINQ有一个鲜为人知的功能 - Zip。该函数采用两个集合并将它们合并为一个集合:
int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };
var numbersAndWords = numbers.Zip(words, (number, word) => new KeyValuePair<string,int>(word, number);
答案 1 :(得分:1)
您的代码编译是因为ViewBag
是dynamic
,这意味着没有编译时检查。
如果您更换了
var keyValuePair = new KeyValuePair<string, double>(ViewBag.NomeDaCapivara, ViewBag.PesoDeCadaCapivaraDoMeuBalaioDeCapivaras);
如果直接放入数组,则会出现预期的编译时错误:例如
var keyValuePair = new KeyValuePair<string, double>(
new string[] { "Jerimúndia", "Genoveva", "Facibulana", "Carnavala", "Dentinhos Dourados", "Creusa" },
new double[] { 500.0, 400.0, 250.0, 12.0, 1589.0, 87.3 });
给出:
Compilation error (line x1, col y1): The best overloaded method match for 'System.Collections.Generic.KeyValuePair<string,double>.KeyValuePair(string, double)' has some invalid arguments
Compilation error (line x2, col y2): Argument 1: cannot convert from 'string[]' to 'string'
Compilation error (line x3, col y3): Argument 2: cannot convert from 'double[]' to 'double'
旧学校,明确的方式是这样的:
var meuBalaioDeCapivaras = new string[]
{
"Jerimúndia", "Genoveva", "Facibulana", "Carnavala", "Dentinhos Dourados", "Creusa"
};
var pesoDeCadaCapivaraDoMeuBalaioDeCapivaras = new double[]
{
500.0, 400.0, 250.0, 12.0, 1589.0, 87.3
};
var list = new List<KeyValuePair<string, double>>();
for (var i = 0; i < meuBalaioDeCapivaras.Length; i++)
{
list.Add(new KeyValuePair<string, double>(meuBalaioDeCapivaras[i], pesoDeCadaCapivaraDoMeuBalaioDeCapivaras[i]));
}
正如Felipe Oriani和Avner Shahar-Kashtan所述,如果您使用的是.NET 3.5或更高版本,则可以使用Linq