Sophie Garcia
Sophie Garcia

Reputation: 125

C# How I should collect the given data from object to another instance?

I have my main object class which contains data of player: name, score and team. I have another container class in which I put all those players. I make some actions with them, like finding who has the biggest score and etc. and everything is fine, but. Somehow, I need to make a list of all containing teams and count amount of score each team has. I would like to ask, what are some methods to do it properly? Because all players maybe can have different teams or all the same team, so it needs to be done without duplicates.

I have tried to make

private string[] Team;

in my Container class, but realized that it will be hell of work and also that would make my class not container.

Here are how my classes look like(I put only a parts of them, not full class, because I think there is no need) without any changes I tried:

class Player
{
        private string name;
        private string team;
        private int score;       
}

class Container
{
        const int Cn = 500;

        private Player[] Pl;

        public int Count { get; set; }

        public Container()
        {
            Count= 0;
            Pl = new Player[Cn];

        }
}

So, let's say I have 2 objects in my Container. The data they contain is:

Name    Score    Team
Matt     15      Alfa
Oreo     5       Beta
Bean     7       Alfa

I wish results to be:

List of teams and their score:
Alfa     22
Beta      5

Upvotes: 2

Views: 102

Answers (1)

Risto M
Risto M

Reputation: 3009

Here is one solution which uses Linq GroupBy and Sum. I made slight modifications on your Player and Container classes as you see (1) List<Player> as data storage instead of Array and (2) public properties in Player class:

class Player
{
    public string Name { get; set; }
    public string Team { get; set; }
    public int Score { get; set; }
}

class Container
{
    private IList<Player> _players;
    public Container()
    {
        _players = new List<Player>();
    }    

    public void Add(Player p) => _players.Add(p);

    public IList<(string Team, int Sum)> GetTeamStats()
    {
        return _players
            .GroupBy(g => g.Team)
            .Select(r => ( Team : r.Key, Sum : r.Sum(s => s.Score)))
            .ToList();
    } 
}

class Program
{
     static void Main(string[] args)
    {
        var cont = new Container();

        cont.Add(new Player { Name = "Matt", Score = 15, Team="Alfa" });
        cont.Add(new Player { Name = "Oreo", Score = 5, Team = "Beta" });
        cont.Add(new Player { Name = "Bean", Score = 7, Team = "Alfa" });

        var teamStats = cont.GetTeamStats();
        foreach (var team in teamStats)
        {
            Console.WriteLine($"{team.Team} {team.Sum}");
        }
    }
}

Output:

Alfa 22 
Beta 5

Upvotes: 5

Related Questions