hristo12319
hristo12319

Reputation: 11

Indexes that correspond to each other in two Lists

I have two Lists:

List<string> names = new List<string>();
List<int> goals = new List<int>();

One of them is a string List while the other one is a int List. I add some numbers in the second List, and then I get the biggest number in the List. This works.

Now I need to type some names in the console and after each name I need to type a certain number and this repeats to whenever I want.

How do I get the index of the biggest number in the second list and to print it alongside the name that actually have "scored" that biggest number? I want to get the index from the first string List that corresponds to the index of the biggest number in the second List. Is there a way that I can do it?

Upvotes: 0

Views: 213

Answers (2)

Fildor
Fildor

Reputation: 16059

In your case, "Name" and "Goals" relate to each other. Someone or something with a "Name" has obviously attached to them a number of "Goals". So, let's reflect this relation in a class:

public class StatisticsItem
{
    // Properties here
    public string Name {get; set;}
    public int Goals {get; set;}
}

You then can create new instances of that class like so:

var item = new StatisticsItem() { Name = "Marc", Goals = 5 };

and you can put those in a list:

var myList = new List<StatisticsItem>();
myList.Add(item);

Find your champion:

using System.Linq;

// ...

Console.WriteLine("Goalie King: {0}", myList.MaxBy(x => x.Goals).Name);

See in action: https://dotnetfiddle.net/I9w5u7


To be a bit more clean, you could of course use a constructor:

public class StatisticsItem
{
    // Properties here
    public string Name {get; set;}
    public int Goals {get; set;}

    public StatisticsItem(string name, int goals)
    {
        Name = name;
        Goals = goals
    }
}

// and then create instances like so:
var item = new StatisticsItem("Marc", 5);

Upvotes: 1

Convel
Convel

Reputation: 144

Can't comment so i will add my opinion here. Fildor suggested 1 list with 2 properties which should cover your case. I would say also check if a dictionary<string, int> or a dictionary<string, List<int>> is a better fit instead of a list. Keep in mind for a dictionary to work the key (name in your case) must be unique. If not discard this answer

Upvotes: 0

Related Questions