打印出不同计数的各种列表的所有项目,用作 c# 中字典中的键

Printing out all the items of various lists of different counts used as keys in a dictionary in c#

class Program
{
    static void Main(string[] args)
    {          
       pnL oldSys1 = new pnL()
        {
            Letters = new List<string>() { 
              "A", "E", "I", "O", "U", "L", "N", "R", "S", "T" },
            Points = 1

        };

        pnL oldSys2 = new pnL()
        {
            Letters = new List<string> { "D", "G" },
            Points = 2
        };


        //Dictionary with list as key
        Dictionary<List<string>, int> newDic = new Dictionary<List<string>, int>();
        newDic.Add(oldSys1.Letters, oldSys1.Points);
        newDic.Add(oldSys2.Letters, oldSys2.Points);

        foreach (KeyValuePair<List<string>, int> oldSysKeyValuePair in newDic)
        {
            int x = 0;

            do { Console.WriteLine(oldSysKeyValuePair.Key[x++] + 
                   " = " + 
                   oldSysKeyValuePair.Value); 
               } 
            while (x < oldSys2.Letters.Count());
            //do { Console.WriteLine(oldSysKeyValuePair.Key[x++]); }
            // while (x < oldSys1.Letters.Count());

        }


    } 

    public class pnL
    {
        public int Points { get; set; }
        public List<string> Letters { get; set; }

    }
}

如果我把上面代码中的注释注释掉,会打印出异常 因为列表的计数不同。我该怎么做?

您得到异常是因为 oldSys1 的计数大于 oldSys2。你应该在 foreach 中使用的变量上循环,像这样..

Dictionary<List<string>, int> newDic = new Dictionary<List<string>, int>();
newDic.Add(oldSys1.Letters, oldSys1.Points);
newDic.Add(oldSys2.Letters, oldSys2.Points);

foreach (KeyValuePair<List<string>, int> oldSysKeyValuePair in newDic)
{
    //int x = 0; //don't need this

    foreach (var key in oldSysKeyValuePair.Key)
    {
        Console.WriteLine(key + " = " + oldSysKeyValuePair.Value);
    }
 }