[英]How can I convert a string[] into a dictionary<int, string> using a separate int[] as the key set?
I know that Linq offers the ToDictionary(key, value)
method, and I'm sure there's a way to be able to do what I'm trying to achieve but I can't quite figure it out. 我知道Linq提供了
ToDictionary(key, value)
方法,并且我敢肯定有一种方法可以完成我想达到的目标,但我还不太清楚。
I have two arrays, the first being conditionalIds
, which is simply an int[]
that stores a number of Ids, the second array is a string[]
called conditionalAnswers
. 我有两个数组,第一个是
conditionalIds
,它只是一个存储大量Ids的int[]
,第二个数组是一个称为conditionalAnswers
的string[]
。 I essentially want to combine and map these two arrays so that each of the Ids stores in conditionalIds maps to the correct answer. 我本质上是想合并并映射这两个数组,以便条件ID中存储的每个ID都映射到正确的答案。
var conditionalIds = _currentRuleSet.MultiConditionalQuestionIds;
var conditionalAnswers = _currentRuleSet.MultiConditionalQuestionAnswers;
var map = conditionalAnswers.ToDictionary(conditionalIds, x => x[]);
However I'm not sure how to structure the Linq query to achieve this. 但是我不确定如何构造Linq查询来实现这一点。
Assuming both lists have the same number of items and they are in the correct order, you want to use Linq Enumerable.Zip
, for example this will give you an IEnumerable
of an anonymous type: 假设两个列表具有相同数量的项目,并且它们的顺序正确,则要使用Linq
Enumerable.Zip
,例如,这将为您提供匿名类型的IEnumerable
:
var map = conditionalIds.Zip(
conditionalAnswers,
(id, answer) => new { id, answer });
And if you really want a dictionary: 如果您真的想要字典:
var dictionary = map.ToDictionary(x => x.id, x => x.answer);
Ans given by @SeM is correct, but one thing is that question id array should have unique values. @SeM给出的答案是正确的,但一件事是问题id数组应具有唯一值。
int[] queId={6,4,9,2,10};
string[] answers ={"Ans1", "Ans3","Ans4","Ans16","Ans18"} ;
Dictionary<int, string> queAnsBank=answers.select((value,index)=>new{Key=queId[index],Value=value}).ToDictionary(i=>i.Key,i=>i.Value);
You can also achieve this by for loop. 您也可以通过for循环来实现。
It looks like target dictionary could be constructed as: 看起来目标字典可以构造为:
Dictionary<int, string> map = conditionalIds.ToDictionary(
keySelector: id => id,
elementSelector: id => conditionalAnswers[id]);
If you are trying to map based on conditionalAnswers
and conditionalIds
indices, you can do something like this: 如果您尝试基于
conditionalAnswers
和conditionalIds
索引进行映射,则可以执行以下操作:
var map = conditionalAnswers
.Select((s, i) => new { Key = conditionalIds[i], Value = s })
.ToDictionary(d => d.Key, d => d.Value);
References: Enumerable.Select Method 参考: Enumerable.Select方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.