[Scala][從C# 到 Scala]Scala:迭代映射 ; C#:遍歷(Forech)

  • 668
  • 0
  • 2014-07-09

[Scala][從C# 到 Scala]Scala:迭代映射 ; C#:遍歷(Forech)

Scala:迭代映射 ; C#:遍歷(Forech)

 

Scala:

   1: var scores=scala.collection.mutable.Map[String,Int]("Alice"-> 10,"Bob"-> 3,"Cindy"-> 8)
   2: //val scores=Map("Alice"-> 10,"Bob"-> 3,"Cindy"-> 8)
   3: //遍歷 key
   4: for (key<-scores.keySet)print(key+" ")
   5: println()
   6:  
   7: //遍歷 value
   8: for (value<-scores.values)print(value+" ")
   9: println()
  10:  
  11: //實驗變數 k 是否為語法糖,結果不是
  12: for (v<-scores)print(v+" ")
  13: println()
  14:  
  15: //實驗變數 k 是否為語法糖,結果不是
  16: for (k<-scores)print(k+" ")
  17: println()
  18:  
  19: //這裡的k,v為語法糖,k代表key、value 代表 value
  20: //可用這句語法 將 key Value 互換
  21: var keyValueChange= for((k,v)<-scores) yield (v,k)
  22: for (v<-keyValueChange.values)print(v+" ")

 

 

Result:

image

 

 

C#:

   1: Dictionary<string,int>scores=new Dictionary<string,int>();
   2: scores.Add("Alice",10); 
   3: scores.Add("Bob", 3); 
   4: scores.Add("Cindy", 8);
   5:  
   6:  foreach (var key in scores.Keys)
   7:  {
   8:      Console.Write(key + " ");
   9:  
  10:  } 
  11: Console.WriteLine();
  12:  
  13: foreach (var value in scores.Values)
  14:  {
  15:      Console.Write(value+" ");
  16:  } 
  17: Console.WriteLine();
  18:  
  19:  
  20: Dictionary<int, string> keyValueChange = new Dictionary<int, string>();
  21: foreach (var item in scores) 
  22: { 
  23:     keyValueChange.Add(item.Value, item.Key);
  24: }
  25: foreach (var value in keyValueChange.Values) 
  26: {
  27:      Console.Write(value + " ");
  28: } 
  29: Console.WriteLine();
  30:  
  31:  
  32: Console.Read();

 

 

Result:

image

 

 

 

By-藍小伙