如何在 C# 中使用函数存储字符串
本文关键字:函数 存储 字符串 | 更新日期: 2023-09-27 18:32:19
我是C#编程的初学者。我对这个简单的程序印象深刻,我想在其中显示符合条件的候选人。我的问题是,在知道候选人符合条件后,我如何存储他/她的姓名。
int eligble = 0; //For counting the eligble Number of candidates
bool retry; //For trying until the Number of eligble candidates is reached
retry = true;
while (retry)
{
string candidatename; //Intilization for Candidate Name ,Date of Birth ,10th and 12th Percentages
int tper, twper;
string dob;
Console.WriteLine("Please enter your Name"); //Getting user input values
candidatename = Console.ReadLine();
Console.WriteLine("Please enter your date of birth in dd/mm/yyyy format");
dob = Console.ReadLine();
DateTime dt = Convert.ToDateTime(dob);
Console.WriteLine("Please enter your 12th percentange");
twper = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Please enter your 10th percentange");
tper = Convert.ToInt16(Console.ReadLine());
int age1 = age(dt);
if (eligble > 5) //Checking whether we have selected the Eligble amount of candidates
{
Console.WriteLine("We have selected five eligble candidtes");
retry = false;
Console.WriteLine("n");
}
else
{
if (age1 > 20 && twper > 65 && tper > 60) //Checking Whether the candidate have satisfiyed the Conditions
{
eligble += 1;
string grad = rade(twper, tper);
}
else
{
eligble -= 1;
}
}
}
}
static int age(DateTime _dt) //Function for calculating the age of the candidate
{
DateTime n = DateTime.Now; // To avoid a race condition around midnight
int age = n.Year - _dt.Year;
if (n.Month < _dt.Month || (n.Month == _dt.Month && n.Day < _dt.Day))
age--;
return age;
}
static string rade(int _tper, int _twper)
{
string grade1;
int avg= ( _tper+_twper)/ 2;
if (avg > 90)
{
grade1 = "a";
return grade1;
}
else if (avg > 80 && avg < 80)
{
grade1 = "b";
return grade1;
}
else if (avg > 70 && avg < 79)
{
grade1 = "c";
return grade1;
}
else
{
grade1 ="d";
return grade1;
}
}
"
商店"具有广泛的含义。您可以在程序运行时将数据存储在内存中。在这种情况下,C# 提供了大量集合。如果您只想保留它们,列表将起作用。
var names = new List<string>();
names.Add(candidate.Name);
如果您更喜欢使用某种键存储它们,然后使用该键从集合中获取值,更好的选择是字典:
var myEligibleCandidates = new Dictionary<string, string>();
myEligibleCandidates[candidate.Id] = candidate.Name;
这些选项将保留应用程序运行时的值。如果您希望在程序未运行后也存储值,则可以使用文件执行此操作。静态File
类可能是一个好的开始:
public void WriteToFile(string path, List<string> names)
{
File.WriteAllText(path, string.Join(";", names));
}
此方法将名称列表作为参数,并将它们写入用分号分隔的文件。 path
是文件的路径。
然后可以选择将数据保存在数据库中。如果这是您要执行的操作,请查看实体框架和 ADO.NET。不过,我会等待这两个选项,直到您更好地了解第一个和第二个解决方案。
创建一个新的List
对象,为此
List<string> eligableCandidates = new List<string>();
然后,当您想向列表中添加某些内容时,请执行以下操作:
eligableCandidates.Add(candidateName);
希望这有帮助,
杰森。