edit: To clarify the question, I'm trying to tighten up my code by storing multiple objects(which all need to be drawn in different positions and manners and each has custom properties such as shape) in a list. I'd like to be able to access one of these properties from any given object in the list for various purposes, such as drawing a sprite unique to that item in the list, later on in my program.
I'm trying to access properties specific to each individual object in a list I've created but can't seem to get it right. I think I'm missing something fundamental with lists! Here's my class where I define the Islands:
class Island
{
public string IslandName { get; set; }
public Vector2 Position { get; set; }
public Rectangle IslandRectangle { get; set; }
public Island(string name, Vector2 position, Rectangle rectangle)
{
name = this.IslandName;
position = this.Position;
rectangle = this.IslandRectangle;
}
}
Then, in my Main method, I create a new list of islands(just one for now):
List<Island> allIslands = new List<Island>()
{
new Island("ShepherdsLookout", new Vector2(200, 200), new Rectangle(200,200, 50, 50))
};
In the draw method of my game, I want to be able to access the rectangle specific to this island, for example instead of writing:
spritebatch.draw(sprite, new vector2D(200, 200), new rectangle(200, 200, 50, 50));
I'd like to just do something like this pseudocode:
spritebatch.draw(sprite, islands.shepherdslookout.position, islands.shepherdslookout.rectangle);
I've tried using IEnumerable to do it:
IEnumerable<Island> ShepherdsLookout = from island in allIslands where island.IslandName == "ShepherdsLookout" select island;
but that doesn't seem to be working either :/ Do I need a foreach loop or something? I feel like theres some way to do it with Linq but I'm not sure.
You could do a couple different things:
Using list
Island theIsland = islands.Find(x => x.IslandName == "ShepherdsLookout");
Using a dictionary will provide better performance.
Dictionary<string, Island> islands = new Dictionary<string, Island>();
//Load dictionary data Island theIsland = islands["ShephardsLookout"];
Either way you would then use just:
theIsland.Position
To retrieve the value