好的,我现在已经在我的头上砸了。
我有两个自定义对象列表,两个列表中的一个属性相同。我需要遍历两个列表并查看属性是否相同。
我可以用嵌套的 for-each 循环来做到这一点,但如果我能用 LINQ 做同样的事情,我很不情愿(我确信我能做到)。我几乎尝试了所有方法,但我根本无法找到我正在寻找的解决方案。
这是我用于列表的对象的代码。
public class Game
{
// Fields
private short maxPlayers;
private Team axis;
private Team allies;
// Properties
public string Name { get; set; }
public short MaxPlayers
{
get
{
return maxPlayers;
}
set
{
if (value > 8)
maxPlayers = 8;
else if (value < 2)
maxPlayers = 2;
else
maxPlayers = value;
}
}
public short CurrentPlayers
{
get
{
int players = axis.Players.Count + allies.Players.Count;
return (short)players;
}
}
public bool IsFull
{
get
{
if (CurrentPlayers == MaxPlayers)
return true;
else
return false;
}
}
public Team Axis { get; set; }
public Team Allies { get; set; }
public List<Player> Players
{
// Somehow this does not work either, so I had to stick with one single team in the for-each loops. Ideas to fix?
get
{
if (allies.Players.Count == 0)
return axis.Players.Concat(allies.Players).ToList();
else
return allies.Players.Concat(axis.Players).ToList();
}
}
//Constructor
public Game()
{
axis = new Team();
allies = new Team();
}
}
public class Team
{
public List<Player> Players { get; set; }
public EFaction Faction { get; set; }
public enum EFaction
{
Allies,
Axis,
Random
}
public Team()
{
Players = new List<Player>();
Faction = EFaction.Random;
}
}
public class Player
{
private int skillRange = 200;
public string Name { get; set; }
public int Skill { get; set; }
public int SkillRange
{
get
{
return skillRange;
}
set
{
if (value >= 200)
skillRange = value;
else
skillRange = 200;
}
}
}
在启动时,我从数据库中填充列表并对列表执行相同操作。我想要做的是遍历游戏列表并将游戏中每个玩家的技能属性与团队中每个玩家的技能属性进行比较。这是我使用的 for-each 循环。这行得通。但是你清楚地可以看到我为什么要如此糟糕地削减它。
// Loop through each player in the Automatch queue.
foreach (Team team in match.TeamsInQueue)
{
// Loop through every game in the Atomatch queue.
foreach (Game game in match.AvailableGames)
{
int teamPlayersInSkillRange = 0;
// Loop through every player in the team and loop through every player in the game.
foreach (Player teamPlayer in team.Players)
{
int gamePlayersInSkillRange = 0;
foreach (Player gamePlayer in game.Allies.Players)
{
// Compare beoth skill values. If they are in a certain range increase the counter.
if (Math.Abs(teamPlayer.Skill - gamePlayer.Skill) <= 200) // The range is currently set for 200, but I want to make it variable later.
gamePlayersInSkillRange++;
}
// Check if the player in the team is in skill range of the game he wants to join. If yes increase the counter.
if (gamePlayersInSkillRange == game.Allies.Players.Count)
teamPlayersInSkillRange++;
}
// Check if the whole team is in skill range of the game they want to join. If yes return true.
if (teamPlayersInSkillRange == team.Players.Count)
{
// ToDo: Implement join process here.
}
}
}
任何帮助,将不胜感激。谢谢。