简体   繁体   中英

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. 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. 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 :/ ...

  1. 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 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 :

  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 ?

Do you mean that Athletes is a List<Athlete> or something of that nature? You can check if any member of a generic list meets a given predicate with .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.

Override Equals() in Athlete class.

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. No need to iterate.

public void Add (Athlete newAthlete) {
    if (newAthelete == null) return;

    if (! athleteList.Contains(newAthlete)) 
       athleteList.Add(newAthlete);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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