Nabil
Nabil

Reputation: 39

Creating a list of strings during run time. C#

What I need to do I create a list of strings during one time. What the project is supposed to do is separate the input into two categories, usernames and usertypes. input will be similar to : john admin smith teacher Allen admin.
output will be like this: admin john, allen.

teacher smith

this is the code that I have right now but I cannot figure out how to add the names to groups during runtime.

       Regex regex = new Regex(@"([A-z]{1,})\s([a-z]{1,})");
        List<string> input= new List<string>();
        List<string> names = new List<string>();
        List<string> groups = new List<string>();

        int i =0;
        string experimentalString=null;
        Console.WriteLine("Please enter the users' names and corresponding groups seperated by a whitespace," +
            " or type sort to show results ");
        while (string.Compare(experimentalString ,"sort")!=0)
        {
            experimentalString = null; 
            experimentalString =  Console.ReadLine();
            Match match = regex.Match(experimentalString);
            if (match.Success)
            {

                input.Add(experimentalString);
                Console.WriteLine(input[i]);
            }
            else 
                throw new Exception ("invalid input format");
            //if (input[i].Equals("sort", StringComparison.OrdinalIgnoreCase))
            //{
            //    break;
            //}
            i++;  
        }
        for (int count = 0; count < input.Count-1; i++)
        {
            names.Add(input[i].Substring(0, input[i].IndexOf(' ')));

            groups.Add(input[i].Substring(input[i].IndexOf(' '), input.Count - 1));
        }

Upvotes: 0

Views: 330

Answers (1)

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

Use Groups property.

foreach(var match in regex.Matches(inputStr).Cast<Match>())
{
    var name = match.Groups[1];
    var type = match.Groups[2];
}

You also need to use a class, you should not use sperate lists.

public class User
{
    public User(string name, string type)
    {
        Name = name;
        Type = type;
    }

    public string Name { get; }
    public string Type { get; }
}

Then you can have list of Users.

List<User> users = new List<User>();

//...

foreach(var match in regex.Matches(inputStr).Cast<Match>())
{
    var name = match.Groups[1];
    var type = match.Groups[2];

     users.Add(new User(name, type));
}

If you want to group users by their type use Linq extension method "GroupBy".

var groups = users.GroupBy(u => u.Type);

 foreach(var group in groups)
 {
     // group contains all users with same type
     foreach(var user in group)
     {
          //...
     }
 }

If you want to save groups in some sort of collection, i suggest you to use Dictionary.

 var dictionary = groups.ToDictionary(g => g.Key, g => g.ToList());

Now you can access to list of users with same type, using Type as key.

 var teachers = dictionary["teacher"];
 var admins = dictionary["admin"];

In order to print User in console you should print properties one by one like this.

Console.WriteLine($"Name: {user.Name}, Type:{user.Type}");

Alternatively you can override ToString in User class.

// Put this method in User class
public override string ToString()
{
   return $"User Name: {Name}, User Type {Type}";
}

Now you can print User easily

  Console.WriteLine(user);

Upvotes: 1

Related Questions