我有以下数据结构:
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
。
现在我的问题是,如果我想要显示哪个玩家与谁一起玩和多久,那么这将是最具逻辑性和易于查询的数据结构。毕竟我想向用户展示一个这样的图表(超级油漆技能):
答案 0 :(得分:2)
作为使您的解决方案更整洁的建议,让Player覆盖等于。代码如下所示:
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();
答案 1 :(得分:0)
您可以使用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