我有一个球员类
public class Player : Person
{
public List<int> SetPoints;
}
游戏类
private List<Player> Players;
public Game(List<Player> players)
{
Players = players;
}
public void Simulate()
{
var winnerPoints = 6;
var looserPoints = Tournament.Random.Next(0, 5);
var winnerId = Players[Tournament.Random.Next(0, 1)].Id;
Players.Where(p => p.Id == winnerId).Select(p => p.SetPoints).Add(winnerPoints);
}
代码演示了我想要完成的内容,但我无法访问所选播放器对象中的更新SetPoints列表。任何人都可以指出我需要进行哪些修改才能使其正常工作?
提前致谢
已更新
我的目标是将winnerPoints
添加到Player
中的一个随机Players
对象的SetPoints,将loserPoints
添加到另一个Players
始终是一个列表两个对象,由构造函数提供)感谢maccettura我使用FirstOrDefault()
完成了这个
public void Simulate()
{
var winnerPoints = 6;
var loserPoints = Tournament.Random.Next(0, 5);
var winnerId = Players[Tournament.Random.Next(0, 1)].Id;
Players.FirstOrDefault(p => p.Id == winnerId).SetPoints.Add(winnerPoints);
Players.FirstOrDefault(p => p.Id != winnerId).SetPoints.Add(loserPoints);
}
答案 0 :(得分:1)
from pylab import *
no_steps = 10000
number = random()
position = zeros(no_steps)
position[0] = 0
time = zeros(no_steps)
time[0] = 0
for i in range(1, no_steps):
time[i] = time[i-1] + 1
if number >= 0.5:
position[i] = position[i-1] + 1
number = random()
else:
position[i] = position[i-1] - 1
number = random()
plot(time, position)
number2 = random()
position2 = zeros(no_steps)
position2[0] = 0
time2 = zeros(no_steps)
time2[0] = 0
for t2 in range(1, no_steps):
time2[t2] = time[t2-1] + 1
if number2 >= 0.5:
position2[t2] = position2[t2-1] + 1
number2 = random()
else:
position2[t2] = position[t2-1] - 1
number2 = random()
plot(time2,position2)
对象:您现在使用的代码不符合您的想法:
Player
这样做是在Players.Where(p => p.Id == winnerId).Select(p => p.SetPoints)
上查找所有匹配,然后选择匹配列表属性的所有。这会产生winnerId
。
如果您只需要一个IEnumerable<List<int>>
,那么您需要使用Player
:
FirstOrDefault()
这会给你一个var player = Players.FirstOrDefault(p => p.Id == winnerId);
//Check if player is not null, then add
作为回报,或者Player
(null)如果没有匹配。
现在您已拥有default(Player)
对象,您可以从那里访问Player
媒体资源和SetPoints
。
Add()
个对象:如果您想要所有匹配的Player
个对象,您只需要迭代Player
个查询结果:
Where()
答案 1 :(得分:1)
假设winnerId
是唯一的,使用FirstOrDefault
找到单个结果就足够了:
Players.FirstOrDefault(p => p.Id == winnerId)?.SetPoints.Add(winnerPoints);
对于案例(或者更确切地说,另一个用例),它不是唯一的,并且您实际上想要结果列表,您可以在调用{后ForEach()
使用ToList()
{1}}(或标准foreach
循环):
Players.Where(p => p.Id == winnerId).ToList().ForEach(p => p.SetPoints.Add(winnerPoints));