Tommy
Tommy

Reputation: 7

Is it possible to store a string and an int in one list?

I want to do a list of scores. In addition, the name of the child should be saved in that list too. After adding scores and names to the list, the list is sorted so that the lowest score is the first entry in the list. But I always get this error message:

Using the generic type 'System.Collections.Generic.List' requires 1 type arguments

What is wrong? Is it not possible to store names and scores in one list? What should I change?

SpriteFont Scores;
Random random = new Random();
List<string> NamesList = new List<string>();
List<string,int> NamesAndPointsList = new List<string,int>();

protected override void LoadContent()
{
  spriteBatch = new SpriteBatch(GraphicsDevice);
  Scores = Content.Load<SpriteFont>("Arial");

  NamesList.Add("Veronica");
  NamesList.Add("Michael");
  NamesList.Add("Christina");

  for (int j = 0; j <= NamesList.Count - 1; j++)
  {
    int Points = random.Next(101);
    NamesAndPointsList.Add(NamesList[j],Points);
  }
  NamesAndPointsList.Sort();
}
protected override void Draw(GameTime gameTime)
{
  GraphicsDevice.Clear(Color.CornflowerBlue);
  spriteBatch.DrawString(Scores, NamesAndPointsList[0].ToString() + ";" + NamesAndPointsList[1].ToString() + ";" + NamesAndPointsList[2].ToString(), new Vector2(200, 200), Color.White);

        base.Draw(gameTime);
}

Upvotes: 0

Views: 157

Answers (2)

Cyral
Cyral

Reputation: 14153

You could use a Tuple, create your own Object, or use a Dictionary, which is ideal for what you are trying to do. A Dictionary will work better in this situation compared to a List because it can easily perform lookups.

The Dictionary type provides fast lookups with keys to get values. With it we use keys and values of any type, including ints and strings.

Dictionary<string,int> Users = new Dictionary<string,int>();

Basicly, the Key which is a string is the username and the Value which is an int is the score.

To add a new user you can do this

 Users.Add("Michael",0); //Create new user named Michael, who starts with 0 points

Now you want to get Michael score possibly, you can quickly find it by doing this

 int Score = Users["Michael"];

I also don't see a need to has a Namesand NameAndPoints list, you can just use one.

Upvotes: 2

TimothyP
TimothyP

Reputation: 21755

The definition is List which indeed requires a single type.

But what is preventing you from defining that type?

public struct User
{
   public string Name { get; set;}
   public int Score { get; set;}
}

var users = List<User>();

or if you do not want to define the class

var users = List<Tuple<string, int>>();

If however you simply want a list that can hold instances of multiple types nothing prevents you from using an ´ArrayList` or List of object.. although I would avoid that.

Upvotes: 4

Related Questions