Simple, Quality, Awesome Software

Back to Procedural Programming

Below is the complete code for the Back to Procedural Programming Try It Out! problem.

using System;
using System.Collections.Generic;
using System.Linq;

namespace QueryExpressions
{
    public class GameObject
    {
        public int ID { get; set; }
        public double X { get; set; }
        public double Y { get; set; }
        public double MaxHP { get; set; }
        public double CurrentHP { get; set; }
        public int PlayerID { get; set; }
    }

    public class Ship : GameObject { }

    public class Player
    {
        public int ID { get; set; }
        public string UserName { get; set; }
        public string TeamColor { get; set; } // A Color class might be better than string here.
    }


    class Program
    {
        static void Main(string[] args)
        {
            List<GameObject> gameObjects = new List<GameObject>();
            gameObjects.Add(new Ship { ID = 1, CurrentHP = 50, MaxHP = 100, PlayerID = 1 });
            gameObjects.Add(new Ship { ID = 2, CurrentHP = 75, MaxHP = 100, PlayerID = 1 });
            gameObjects.Add(new Ship { ID = 3, CurrentHP = 0, MaxHP = 100, PlayerID = 2 });
            gameObjects.Add(new Ship { ID = 3, CurrentHP = 100, MaxHP = 100, PlayerID = 2 });
            gameObjects.Add(new Ship { ID = 3, CurrentHP = 100, MaxHP = 200, PlayerID = 2 });

            List<Player> players = new List<Player>();
            players.Add(new Player { ID = 1, UserName = "Player 1", TeamColor = "Red" });
            players.Add(new Player { ID = 2, UserName = "Player 2", TeamColor = "Blue" });


            // The Select is not strictly necessary. You could leave it off with the same
            // results, but I've left it in to illustrate the conversion from query
            // syntax to method call syntax a little more directly.
            var results = gameObjects.Where(o => o.CurrentHP > 0).Select(o => o);

            Console.ReadKey();
        }
    }
}