【问题标题】:How can I use dictionary to map keys located in one string list to values located in another string list using C#?如何使用字典将位于一个字符串列表中的键映射到使用 C# 位于另一个字符串列表中的值?
【发布时间】:2019-04-11 20:46:46
【问题描述】:

我有两个字符串列表; myFruits 和 myColors。

myFruits 的格式如下:

 ["Apple", "Banana", "Guava", "Blueberry"] //key

myColors 的格式如下:

["Red", "Yellow", "Green", "Blue"]  //value

我希望能够使用字典将 myFruits 的键连续映射到 myColors 的值并获取 在我的输出中类似于以下内容。

Apple:Red
Banana:Yellow
Guava:Green
Blueberry:Blue

我尝试在我的代码中使用 zip,但我做的事情不正确,因为它没有正确打印。

var dic = myFruits.Zip(myColors, (k, v) => new { k, v }).ToDictionary(x => x.k, x => x.v); 

我怎样才能达到预期的输出?这只是一个示例,我可以在每次运行时在我的列表中有多个值,但总会有相等的否。无论数量是多少,这两个列表上的项目。任何帮助将不胜感激。

【问题讨论】:

  • 你是如何打印它的,它显示了什么?您对Zip 的使用看起来不错。
  • 我没有正确打印它。它现在可以正常工作。谢谢!

标签: c# string list dictionary


【解决方案1】:

这看起来更像是一个输出问题。请参阅下面的代码来制作<fruit>:<color> 字符串。

var myFruits = new []{"Apple", "Banana", "Guava", "Blueberry"};
var myColors = new []{"Red", "Yellow", "Green", "Blue"};

var dic = myFruits.Zip(myColors, (k, v) => new { k, v }).ToDictionary(x => x.k, x => x.v);

foreach(var kvp in dic)
{
    Console.WriteLine($"{kvp.Key}:{kvp.Value}");
}

输出:

Apple:Red
Banana:Yellow
Guava:Green
Blueberry:Blue

【讨论】:

  • 确实是输出问题。我没有正确打印出来。现在工作正常。谢谢!
【解决方案2】:

您是否有不使用 LINQ 扩展的问题?

var myFruits = new [] {"Apple", "Banana"};
var myColors = new [] {"Red", "Yellow"};
var mapping = new Dictionary<string, string>();

for(var i = 0; i < myFruits.Count(); i++)
{
  mapping.Add(myFruits[i], myColors[i]);
}

【讨论】:

  • 风格太老了! (与 Linq Zip 方式相比,也太可读了)。 Linq 很棒,但接受的 var dic = myFruits.Zip(myColors, (k, v) =&gt; new { k, v }).ToDictionary(x =&gt; x.k, x =&gt; x.v); 是否比您的 3 行代码更好?我不这么认为
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多