检查输入是否与列表匹配

时间:2015-06-14 00:57:49

标签: c# list

我使用了两个列表,我不知道用什么方法来打印输入。基本上我想首先显示所有月份,然后让用户选择一个月并显示日期。

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Choose a month: ");
            Console.ReadLine();

            List<int> list = new List<int> { 31, 28, 31, 30, 31, 30, 31, 31, 30, 30, 30, 31 };
            List<string> Manad = new List<string> { "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December" };

            string inmat;
            inmat = Console.ReadLine();

            if (inmat == 31) ;
            {
                Console.WriteLine(Manad[0] + " " + list[0]);
                Console.ReadLine();
            }
        } 
    }
}

2 个答案:

答案 0 :(得分:1)

使用两个列表最好使用类似下面代码的字典

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            Console.WriteLine("Choose a month: ");
            Console.ReadLine();

            Dictionary<string,int> dict = new Dictionary<string,int>(){
                {"Januari", 31},  
                {"Februari", 28},
                {"Mars", 31},
                {"April", 30},
                {"Maj", 31},
                {"Juni", 30},
                {"Juli", 31},
                {"Augusti", 31},
                {"September", 30},
                {"Oktober", 31},
                {"November", 30},
                {"December", 31}
            };

            int nummberOfDays = dict["Maj"];

            int inmat = int.Parse(Console.ReadLine());
            //get all the months with days = inmat
            Console.WriteLine(string.Join(",", dict.AsEnumerable().Where(x => x.Value == inmat).Select(y => y.Key).ToArray()));
            Console.ReadLine();

        }


    }

}
​

答案 1 :(得分:0)

在不破坏乐趣并为您工作的情况下,您希望了解foreach

List<string> demo_list = new List<String> {"hello", "world", "!"};

foreach (var s in demo_list)
{
    Console.WriteLine(s);
}
相关问题