[英]Validating a String in a Class List C#
Im making a project in C# Console Application and it is a Sports Club Management Software for school. 我在C#控制台应用程序中制作了一个项目,它是学校的运动俱乐部管理软件。 I created a Class List Athletes and I got several paramenters, one of it is the Athlete's ID... My question is, when I choose the "Add Athlete" option, how can I check if there´s already an ID in the whole list.
我创建了一个班级列表运动员,我有几个参数,其中之一是运动员的ID ...我的问题是,当我选择“添加运动员”选项时,如何检查整个ID是否已经存在名单。 You probably thinking: "Ohh... Well its preety ez, just a do while, and a for method in it and use the Contain method..." Well Ive tryed that and I didn't quite got it... Ive been programming for some months now... Its not that I am a very skilled programmer but :/ ...
您可能会想:“哦,好吧,它漂亮的ez,只是执行一会儿,并在其中使用for方法并使用Contain方法...”好吧,我尝试过,但我还不太清楚...现在已经编程了几个月了...不是我是一个非常熟练的程序员,而是:/ ...
This is what I tryed doing: 这是我尝试做的:
do { for (int i = 0; i < Athletes.Count; i++) { if (Athletes[i].id.Contains(id)) { Console.WriteLine("ID already exists, please insert another ID!"); Console.WriteLine(); Console.Write("Id: "); id = Console.ReadLine(); } } } while (Athletes[i]);
the thing is, as you can see, I cant use the [i] in the do while what makes it impossible to go through the list. 事实是,正如您所看到的,我无法在执行操作时使用[i],这使得无法浏览列表。 I thought about getting a boolean but Im not really into booleans.
我考虑过要使用布尔值,但是我不是很喜欢布尔值。 Its probably a preety ez to fix problem but I really cant figger it out.
这可能是解决问题的先决条件,但我真的无法解决。 Thanks guys.
多谢你们。 :)
:)
Try using Linq : 尝试使用Linq :
using System.Linq;
...
// Keep asking id...
while (true) {
if (!Athletes.Any(athlete => athlete.ID == id))
break; // ... until id is not found
Console.WriteLine("ID already exists, please insert another ID!");
Console.WriteLine();
Console.Write("Id: ");
id = Console.ReadLine();
//TODO: validate id here
}
Please notice, that you have to validate the user input: what if user write, say "bla-bla-blas"
as id
? 请注意,您必须验证用户输入:如果用户输入
id
为"bla-bla-blas"
,该怎么办?
Do you mean that Athletes
is a List<Athlete>
or something of that nature? 您是说
Athletes
是List<Athlete>
还是类似的东西? You can check if any member of a generic list meets a given predicate with .Any()
. 您可以使用
.Any()
检查泛型列表的任何成员是否满足给定谓词。 For example: 例如:
if (Athletes.Any(a => a.id == id))
If Any()
returns true
then that means at least one member of the list satisfies the condition. 如果
Any()
返回true
则意味着列表中至少一个成员满足条件。
Override Equals()
in Athlete class. 在Athlete类中重写
Equals()
。
public override bool Equals (Object otherAthlete) {
if (otherAthlete == null) return false;
if (! otherAthlete is typeof(Athlete)) return false;
return this.ID == otherAthlete.ID;
}
That will make List<Athelete>.Contains()
work. 这将使
List<Athelete>.Contains()
工作。 No need to iterate. 无需重复。
public void Add (Athlete newAthlete) {
if (newAthelete == null) return;
if (! athleteList.Contains(newAthlete))
athleteList.Add(newAthlete);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.