【问题标题】:Find out which players I've already met找出我已经遇到的玩家
【发布时间】:2016-10-10 19:57:17
【问题描述】:

我有以下数据结构:

public class Match
{

    public List<Player> Participants;

}

public class Player
{

    public string Name;

}

现在我得到了以下示例数据:

Match 1
 - PlayerA
 - PlayerB
 - PlayerC

Match 2
 - PlayerA
 - PlayerB
 - PlayerD
 - PlayerE

根据此数据,如果PlayerA 想知道他与哪些玩家一起玩,答案将是PlayerB, PlayerC, PlayerD and PlayerE

我现在的问题是,如果我想显示哪个玩家和谁一起玩多久玩一次,最符合逻辑和最容易查询的数据结构是什么。毕竟我想向用户展示这样的图表(超级绘画技巧):

【问题讨论】:

  • 让每个玩家维护一个List&lt;T&gt;,其中包含他们遇到的人的姓名/ID。对于多久T 必须包含一个计数器

标签: c# data-modeling


【解决方案1】:

作为使您的解决方案更整洁的建议,让 Player 覆盖 Equals。代码如下所示:

public class Player
{
    public override bool Equals(object obj)
    {
        var other = obj as Player;
        if (other == null)
            return false;
        return this.Name == other.Name;
    }

    public override int GetHashCode()
    {
        return this.Name.GetHashCode();
    }

    public string Name;
}

这使您可以按照本文的思路制定更具可读性的寻找对手的解决方案

Player me = new Player { Name = "Me" };
var allMatches = new List<Match>
{
    new Match
    {
        Participants = new List<Player> 
        {
            me,
            new Player { Name = "Some Other Dude"}
        }
    },

    new Match
    {
        Participants = new List<Player>
        {
            me,
            new Player { Name = "My Rival" }
        }
    }
};

var myMatches = allMatches.Where(m => m.Participants.Contains(me)).ToList();
var myOpponents = myMatches.SelectMany(m => m.Participants.Except(new [] {me})).Distinct();

【讨论】:

    【解决方案2】:

    你可以这样做,使用Linq

    List<List<Match> matches = ...
    string player = "playerA";
    
    var coplayers = matches.Where(x=>x.Any(p=>p.Participants.Any(s=>s.Name == player))) // get all participants where group contains participant.
               .SelectMany(x=> x.SelectMany(p=>p.Participants))                         // get all participants where group contains participant.
               .Where(x=>x.Name != player)                                              // List co participants 
               .GroupBy(x=>x.Name)                                                      // Distinct by grouping on Name or( need to override equal)
               .Select(x=>x.FirstOrDefault())
               .ToList()    
    

    查看Demo

    【讨论】:

      猜你喜欢
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 2022-12-19
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      相关资源
      最近更新 更多