0
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
string[] strings = { "zero", "one", "two", "three", "four", "five", "six",
                     "seven","eight", "nine" };

 var textNums =
                from n in numbers
                select strings[n];

   Console.WriteLine("Number strings:");

   foreach (var s in textNums)
   {
                Console.WriteLine(s);
   }

1)将“整数”转换为表示“单词”中的整数的机制是什么?

2) 只有 int 到 string 才有可能进行这种转换?或者我们可以从这种转变中获得乐趣吗?

4

4 回答 4

7
  1. 这只是数组访问——它使用“数字”中的元素作为“字符串”数组的索引。

  2. 只有整数适用于数组,但您同样可以使用 aDictionary<string, string>或任何东西来进行任意映射。在这种情况下,您可以将字符串数组视为类似于Dictionary<int, string>. 你也可以这样重写:

    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
    var words = new Dictionary<int, string>
    {
        { 0, "zero" },
        { 1, "one" },
        { 2, "two" },
        { 3, "three" },
        { 4, "four" },
        { 5, "five" },
        { 6, "six" },
        { 7, "seven" },
        { 8, "eight" },
        { 9, "nine" }
    };
    var textNums = from n in numbers
                   select words[n];
    

    Console.WriteLine("数字字符串:");

    foreach (var s in textNums) { Console.WriteLine(s); }

那仍然使用整数 - 但是您可以对键是其他类型的字典做同样的事情。

于 2009-10-16T16:38:36.463 回答
5

不,字符串表示只是按照正确的顺序而已。这里没有魔法。

查看字符串数组

strings[0] = "zero";
strings[1] = "one";
strings[2] = "two";
.
.

正确排序的事实是映射起作用的原因。

于 2009-10-16T16:37:37.420 回答
2

当您说 strings[n] 时,您正在访问数组的第 n 个值,并且数组的排序如下:

字符串[0] =“零”;字符串[1] =“一个”;...字符串[4] =“四个”;

所以,这里没有魔法,只是一个有序数组:P

于 2009-10-16T16:43:31.320 回答
1

我会做以下事情:

public enum MyNumberType { 
        Zero = 0, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
        }

您可以通过以下方式对它进行任何操作:

namespace ConsoleApplication
{
    class Program
    {
        public enum MyNumberType { Zero = 0, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten }

        private static int GetIntValue(MyNumberType theType) { return (int) theType; }
        private static String GetStringValue(MyNumberType theType) { return Enum.GetName(typeof (MyNumberType),theType); }
        private static MyNumberType GetEnumValue (int theInt) {
            return (MyNumberType) Enum.Parse( typeof(MyNumberType), theInt.ToString() ); }

        static void Main(string[] args)
        {
            Console.WriteLine( "{0} {1} {2}", 
                GetIntValue(MyNumberType.Five), 
                GetStringValue( MyNumberType.Three),
                GetEnumValue(7)
                );
            for (int i=0; i<=10; i++)
            {
                Console.WriteLine("{0}", GetEnumValue(i));
            }
        }
    }
}

产生以下输出:

5 Three Seven
Zero
One
Two
Three
Four
Five
Six
Seven
Eight
Nine
Ten

这可以扩展到更大的数字和不在连续范围内的数字,如下所示:

public enum MyNumberType { 
        ten= 10, Fifty=50, Hundred=100, Thousand=1000
        }

枚举可以与其他类型一起使用,而不仅仅是 int 类型,所以这非常灵活。

于 2009-10-16T17:33:35.400 回答