我假设你想存储所有玩家及其各自的起点坐标在字典中的映射。该代码,这看起来像:
Dictionary<int, string> startingpoints = xml.Elements(ns + "startingPoint")
.Select(sp => new {
Player = (int)(sp.Attribute("player")),
Coordinates = (string)(sp.Attribute("coordinates"))
})
.ToDictionary(sp => sp.Player, sp => sp.Coordinates);
更妙的是,你有一类用于存储的坐标,如:
class Coordinate{
public int X { get; set; }
public int Y { get; set; }
public Coordinate(int x, int y){
X = x;
Y = y;
}
public static FromString(string coord){
try
{
// Parse comma delimited integers
int[] coords = coord.Split(',').Select(x => int.Parse(x.Trim())).ToArray();
return new Coordinate(coords[0], coords[1]);
}
catch
{
// Some defined default value, if the format was incorrect
return new Coordinate(0, 0);
}
}
}
然后,你可以解析字符串为坐标马上:
Dictionary<int, string> startingpoints = xml.Elements(ns + "startingPoint")
.Select(sp => new {
Player = (int)(sp.Attribute("player")),
Coordinates = Coordinate.FromString((string)(sp.Attribute("coordinates")))
})
.ToDictionary(sp => sp.Player, sp => sp.Coordinates);
然后,您可以访问玩家坐标如下:
Console.WriteLine(string.Format("Player 1: X = {0}, Y = {1}",
startingpoints[1].X,
startingpoints[1].Y));
应该得到的解释是什么样的?玩家作为键和他们的坐标值? – 2010-04-08 17:11:49
是的,确切地说。这将通过一个getter传递出去,调用函数可以解析它,但是它需要。 – NateD 2010-04-08 18:21:58