如何unifiy词典中的两个阵列? [英] How to unifiy two arrays in a dictionary?
问题描述
如果你有两个数组的String []一个
和 INT [] b
你怎么能得到一个字典<字符串,整数>
从它最有效和最少的代码,可能吗?假设它们含有相同数量的元素。
例如,这是最好的方法是什么?
词典<字符串,整数>瓦尔斯=新词典<字符串,整数>();
的for(int i = 0; I<大小;我++)
{
vals.Add(A [I],B [I]);
}
如果你的目标是相匹配在序列中的位置,可以使用 Enumerable.Zip
。
INT [] myInts = {1,2};
的String [] = myStrings {富,酒吧};
VAR词典= myStrings.Zip(myInts,(S,I)=>新建{S,I})
.ToDictionary(项目=> item.s,项目= GT ; item.i);
和因为你使用数组时,写它手写还真是没有那么长。但是,要验证事先阵列真正的长度相等
VAR词典=新词典<字符串,整数>( );
为(INT指数= 0;指数 - LT; myInts.Length;指数++)
{
dictionary.Add(myStrings [指数],myInts [指数]);
}
一般情况下,LINQ的可能会导致更多的表现力,更容易理解的代码。在这种情况下,这是值得商榷的情况正好相反。
If you have two arrays string[] a
and int[] b
how can you get a Dictionary<string,int>
from it most efficiently and with least code possible? Assume that they contain the same number of elements.
For example, is this the best way?
Dictionary<string,int> vals = new Dictionary<string,int>();
for(int i = 0; i < size; i++)
{
vals.Add(a[i],b[i]);
}
If your goal is to match at positions within the sequences, you can use Enumerable.Zip
.
int[] myInts = { 1, 2 };
string[] myStrings = { "foo", "bar"};
var dictionary = myStrings.Zip(myInts, (s, i) => new { s, i })
.ToDictionary(item => item.s, item => item.i);
And since you are working with arrays, writing it "longhand" really isn't all that long. However, you want to validate beforehand the arrays truly are equal in length.
var dictionary = new Dictionary<string, int>();
for (int index = 0; index < myInts.Length; index++)
{
dictionary.Add(myStrings[index], myInts[index]);
}
Usually, Linq can result in more expressive, easier to understand code. In this case, it's arguable the opposite is true.
这篇关于如何unifiy词典中的两个阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!