简体   繁体   English

C#如何使此代码更好或更短?

[英]C# How can I make this code better or shorter?

so I basically just started learning computer programming (C#), and today I got to learn about Arrays . 所以我基本上只是开始学习计算机编程(C#),今天我开始学习Arrays I kinda, sorta, understand what Arrays are , I know they are used for a way of keeping track of a list or collection of many related things all together. 我有点儿理解了什么是数组 ,我知道它们用于跟踪列表或许多相关事物的集合。 So I was thinking of making a program which asks the user for his name and after you put your name it would automatically give you the score that you got on "the test" so I wanna show you guys my code and I'll love some feedback on how can I make my code look better and shorter I guess.. anyways here's my code. 因此,我正在考虑编写一个程序来询问用户的姓名,输入您的姓名后,它将自动为您提供您在“测试”中获得的分数,因此我想向大家展示我的代码,我会喜欢的关于我如何使我的代码看起来更好和更短的反馈,无论如何,这是我的代码。

        string studentNumberOne = "Miguel"; 
        string studentNumberTwo = "Maddie";
        string studentNumberThree = "John";
        string studentName = ""; // Empty string variable for user input...


        int[] grades = new int[3] { 90, 85, 70 }; // arrays, grades for each students...

        Console.WriteLine("Please enter your name: "); // Asking the user to type his/her name
        studentName = Convert.ToString(Console.ReadLine()); //


        if (studentName == studentNumberOne) 
        {
            Console.WriteLine(studentNumberOne + " your score was " + grades[0]);

        }

        else if (studentName == studentNumberTwo)
        {
            Console.WriteLine(studentNumberTwo + " your score was " + grades[1]);

        }

        else if (studentName == studentNumberThree)
        {
            Console.WriteLine(studentNumberThree +" your score was " + grades[2]);
        }



    }
}

I know there's a lot of if/else if's and that's why I'm asking for some feedback on how I can make this code better or shorter, I'm pretty sure there has to be a way with Arrays where you can store all three names that I have in my code and also give them their correspondent score, so yeah, I'll love the feedback, thank you! 我知道有很多if / else if,这就是为什么我要就如何使此代码变得更好或更短寻求一些反馈,我敢肯定, Arrays必须有一种方法可以存储所有这三个代码我在代码中使用的名字,并给他们对应的分数,是的,我喜欢反馈,谢谢! Also try to not go with crazy answer or too much details I guess, like I said I just started learning C# so try to make it as simple as possible so I can understand better (If you can or want). 也要尝试不要回答疯狂的答案或我想太多的细节,就像我说过我刚开始学习C#一样,因此请尝试使其尽可能简单,以便更好地理解(如果可以或想要)。

PD : Sorry for my bad grammar, English is not my first language. PD:对不起,我的语法不好,英语不是我的母语。

You can create a class representing the student information such as Name and Grades. 您可以创建一个代表学生信息的班级,例如姓名和年级。 Have student information stored in a list of student objects. 将学生信息存储在学生对象列表中。 Use LINQ to filter the list based on the student name. 使用LINQ根据学生姓名过滤列表。

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

class Program
{
    static void Main(string[] args)
    {
        List<Student> students = new List<Student>
        {
            new Student {Name = "Miguel", Grades = 90},
            new Student {Name = "Maddie", Grades = 70},
            new Student {Name = "John", Grades = 65},
            new Student {Name = "Isabella", Grades = 80},
            new Student {Name = "Raul", Grades = 75}
        };

        Console.WriteLine("Please enter your name: "); // Asking the user to type his/her name
        string studentName = Console.ReadLine(); //

        var student = students.FirstOrDefault(std => std.Name == studentName);
        if (student != null)
        {
            Console.WriteLine(studentName + " your score was " + student.Grades);
        }
    }
}

public class Student
{
    public string Name { get; set; }

    public int Grades { get; set; }
}

The general rule is to never copy and paste similar code over and over again . 通常的规则是永远不要一遍又一遍地复制和粘贴类似的代码 This is the reason arrays and loops exist. 这就是数组和循环存在的原因。 Put the students in an array and look through them to find a match 将学生排列成阵列,并浏览他们以查找匹配项

class Program
{
    static void Main(string[] args)
    {
        string[] students=new string[] {
            "Miguel", "Maddie", "John", "Isabella", "Raul" };

        int[] grades=new int[] { 
            90, 85, 70, 92, 87 }; // arrays, grades for each students...

        Console.WriteLine("Please enter your name: "); // Asking the user to type his/her name
        string studentName=Console.ReadLine(); //

        for (int i=0; i<students.Length; i++)
        {
            if (students[i].Equals(studentName))
            {
                Console.WriteLine(studentName+" your score was "+grades[i].ToString());
            }
        }

    }
}

Edit 1 编辑1

OF course the CRL has a Dictionary object for connecting for example names to grades. 当然,CRL具有一个Dictionary对象,用于将示例名称连接到成绩。 This is far more efficient and flexible than maintain two separate arrays. 这比维护两个单独的阵列要高效和灵活得多。 See example below: 请参见下面的示例:

    static void Main(string[] args)
    {
        Dictionary<string, int> grades=new Dictionary<string, int>();
        grades["Miguel"] = 90;
        grades["Maddie"] = 85;
        grades["John"] = 70;
        grades["Isabella"] = 92;
        grades["Raul"] = 87;

        Console.WriteLine("Please enter your name: "); // Asking the user to type his/her name
        string studentName=Console.ReadLine(); //

        if (grades.ContainsKey(studentName))
        {
            Console.WriteLine(studentName+" your score was "+grades[studentName]);
        }
    }

You can try this one. 你可以试试这个。

using System;
using System.Collections.Generic;
class Program
{
    static void Main(string[] args)
    {
        List<string> students = new List<string> {
            "Miguel", "Maddie", "John", "Isabella", "Raul" };

        int[] grades=new int[] { 
            90, 85, 70, 92, 87 }; // arrays, grades for each students...

        Console.WriteLine("Please enter your name: "); // Asking the user to type his/her name
        string studentName=Console.ReadLine();
        try{
          Console.WriteLine(studentName+" your score was "+grades[students.IndexOf(studentName)].ToString());
          }
          catch(Exception){
            Console.WriteLine("name Not found");
          }
    }
}

You can change the exception to IndexOutOfRangeException if you need more accurate error tracking. 如果需要更准确的错误跟踪,可以将异常更改为IndexOutOfRangeException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM