Many-to-many relationship in oop

后端 未结 7 782
北恋
北恋 2021-02-04 15:53

what is best way to model many-to-many relationship?

lets say we have a two classes , Team and Player

  • any given P
7条回答
  •  佛祖请我去吃肉
    2021-02-04 16:08

    Relationship between players and teams form Bipartite Graph. Expecting comments(and downvotes?)! I am OOD noob.

        class MyPlayer
        {
            public string Name { get; set; }
    
            public MyPlayer(string n)
            {
                Name = n;
            }
        }
    
        class MyTeam
        {
            public string Name { get; set; }
    
            public MyTeam(string n)
            {
                Name = n;
            }
        }
    
        class PlayerTeamPair
        {
            public MyPlayer Player { get; set; }
            public MyTeam Team { get; set; }
    
            public PlayerTeamPair(MyPlayer p,MyTeam t)
            {
                Player = p;
                Team  = t;
            }
        }
    
        class PlayerTeamBipartiteGraph
        {
            public List Edges { get; set; }
    
            public PlayerTeamBipartiteGraph()
            {
                Edges = new List();
            }
    
            public void AddPlayerAndTeam(MyPlayer p, MyTeam t)
            {
                Edges.Add(new PlayerTeamPair(p, t));
            }
    
            public List GetTeamList(MyPlayer p)
            {
                var teams = from e in Edges where e.Player == p select e.Team;
                return teams.ToList();
            }
    
            public List GetPlayerList(MyTeam t)
            {
                var players = from e in Edges where e.Team == t select e.Player;
                return players.ToList();
            }
    
        }
    
    
        class Program
        {
            static void Main(string[] args)
            {
                var G = new PlayerTeamBipartiteGraph();
    
                MyPlayer a = new MyPlayer("A");
                MyPlayer b = new MyPlayer("B");
                MyPlayer c = new MyPlayer("C");
                MyPlayer d = new MyPlayer("D");
    
                MyTeam t1 = new MyTeam("T1");
                MyTeam t2 = new MyTeam("T2");
    
                G.AddPlayerAndTeam(a, t1);
                G.AddPlayerAndTeam(b, t1);
                G.AddPlayerAndTeam(c, t1);
                G.AddPlayerAndTeam(b, t2);
                G.AddPlayerAndTeam(d, t2);
    
                G.GetTeamList(b).ForEach(t => Console.Write(" {0} ",t.Name));
                Console.WriteLine();
                G.GetPlayerList(t2).ForEach(p => Console.Write(" {0} ",p.Name));
                Console.WriteLine();
            }
        }
    

提交回复
热议问题