I have a data set.
public class EmployeeRepository
{
public static List<Employee> AllEmployees()
{
var loc1 = new List<Location> { new Location { City = "Gretna", State = "VA", ZipCode = "24587" }, new Location { City = "Charlotte", State = "NC", ZipCode = "28012" } };
var loc2 = new List<Location> { new Location { City = "Boston", State = "MA", ZipCode = "02333" }, new Location { City = "Waldham", State = "MA", ZipCode = "02323" } };
var loc3 = new List<Location> { new Location { City = "Greenville", State = "NC", ZipCode = "29011" }};
var loc4 = new List<Location> { new Location { City = "Greenville", State = "SC", ZipCode = "26000" }, new Location { City = "Charleston", State = "SC", ZipCode = "26011" } };
return new List<Employee>()
{
new Employee {Id = 1, Department = new Department{Id = 1, Name = "Technology" }, Locations = loc1 },
new Employee {Id = 2, Department = new Department{Id = 1, Name = "Technology" }, Locations = loc2},
new Employee {Id = 3, Department = new Department{Id = 1, Name = "Technology" }, Locations = loc3 },
new Employee {Id = 4, Department = new Department{Id = 2, Name = "IT" }, Locations = loc4 },
new Employee {Id = 5, Department = new Department{Id = 2, Name = "IT" }, Locations = loc4 },
new Employee {Id = 6, Department = new Department{Id = 3, Name = "Sales" }, Locations = loc3 },
new Employee {Id = 7, Department = new Department{Id = 3, Name = "Sales" }, Locations = loc2},
new Employee {Id = 9, Department = new Department{Id = 4, Name = "Marketing" }, Locations = loc2 },
new Employee {Id = 9, Department = new Department{Id = 4, Name = "Marketing" }, Locations = loc1 },
};
}
}
Now I want to return all locations if the department name is given. My code is working
public List<Location> GetLocations(string name)
{
List<Location> locations = new List<Location>();
var collection = EmployeeRepository.AllEmployees();
var temp = (from e in collection where e.Department.Name == name select e);
foreach(var item in temp)
{
locations.AddRange(item.Locations);
}
return locations.Distinct().ToList();
}
But is there a better way in one linq query/method to do that?
UPDATE:
public class Employee
{
public int Id { get; set; }
public Department Department { get; set; }
public List<Location> Locations { get; set; }
public decimal Salary { get; set; }
}
public class Location
{
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
}