Say I have an Employee class and one of its properties is of type Department. In my GUI, I want to create a new Employee and I instantiate it. I have a collection displayed through a ComboBox of Department objects, so that the end-user can select (assign) a Department for each Employee.
My question is, say when I instantiate this Employee class and I want to default the Department to some value, say "Finance" which is for the Department.Code property.
How can I do this?
I tried but doesn't seem to like when saving:
this.Employee = Employee.CreateEmployee("-1", DateTime.Now, "Active", ...);
this.Employee.Department= new Department { Code = "Finance" };
Any advice will be greatly appreciated.
Generally classes are built with constructors; ie
public class Department
{
string _code = "";
public Department() {}
public Department(string code) {
_code = code;
}
}
So that when your program creates a new department object, you can do:
Department finance = new Department("Finance");
this.Employee = Employee.CreateEmployee("-1", DateTime.Now, "Active", ...);
this.Employee.Department= finance;
Edit: You'd probably be better off using enumerators for this, such that you can declare an enumerator:
public enum Departments
{
Finance,
Technology,
Sales
}
public class Employee
{
Departments _employeeDepartment;
public Employee() {}
public Employee(Department EmployeeDepartment)
{
_employeeDepartment = EmployeeDepartment;
}
}
Related
How can I box the result of a LINQ select into multiple objects? With the following select clause:
select new {
Person = new Person((String)al.Element("firstName"), (String)al.Element("lastName")),
TimePeriod = new TimePeriod((String)al.Element("start"), (String)al.Element("end"))
};
In the example snippet above, Person and TimePeriod are totally unreleated object. Coming from a Scala background, I would have been happy if the result would be boxed into a tuple. Since I'm new to C#, can anyone help me with this?
If you want to put them into a Tuple you can do this
select Tuple.Create(new Person(...), new TimePeriod(...));
But it would be more advisable to create your own class
public class PersonAndTime
{
public PersonAndTime(Person person, TimePeriod timePeriod)
{
Person = person;
TimePeriod = timePeriod;
}
public Person Person{ get; private set; }
public TimePeriod TimePeriod {get; private set; }
}
And do this
select new PersonAndTime(new Person(...), new TimePeriod(...));
If you don't need to pass the results of the query into or out of a method then leaving it in the anonymous class should be fine.
I have a class that has the following syntax:-
public class CorporateTeamTimeSheetTotalsForSpecifiedTimeFrame
{
private List<EmployeeMini> _EmployeesList = new List<EmployeeMini>();
private List<HolidayCalendar> _Holidays = new List<HolidayCalendar>();
public List<EmployeeMini> EmployeeList
{
get { return _EmployeesList; }
set { _EmployeesList = value; }
}
}
Now I want to access these holidays in individual employee mini i.e. for individual employee.
How can i do that?
Regards
Abhishek
This code clearly does not show any relationship between Employees and Holidays. You may simplify this further by associating each EmployeeMini with HolidaysList and then creating a list of EmployeeMini, as:
public class EmployeeMini
{
// ...
private List<HolidayCalendar> _Holidays = new List<HolidayCalendar>();
// ...
}
public class CorporateTeamTimeSheetTotalsForSpecifiedTimeFrame
{
private List<EmployeeMini> _EmployeesList = new List<EmployeeMini>();
public List<EmployeeMini> EmployeeList
{
get { return _EmployeesList; }
set { _EmployeesList = value; }
}
}
Assuming _Holidays is a list of employee holidays and not company holidays.
Please take this solution as a starting point and not as a copy-paste solution.
Edit:
If data of holidays is same for all employees, you may create a separate entity Holidays. You do not have to associate this with the employees. This seems to be a TimeSheet application.
You may associate time entries with Employees, Tasks (which is generally the case) and Holidays.
I have an object
public class School
{
public Employee Emp{get;set;}
public string City{get;set;}
}
public class Employee
{
public string Name{get;set;}
}
Using reflection I need to fetch this Employee Name from the school object
I Tried
School schl=New School();schl.Employee=new Employee{Name="Shalem"};
var empName= schl.GetType().GetProperty("Emp.Name").GetValue(schl, null)
Also tried
PropertyDescriptorCollection allProp= TypeDescriptor.GetProperties(schl);
var empName=allProp["Emp.Name"].GetValue(schl);
I always get null. How can i get?
Note: The thing is i dont know what object it will contain. But all i know is i will get the exact name with inner object like "Emp.Name" etc. Need a generic solution
School schl=New School();
schl.Employee=new Employee{Name="Shalem"};
var emp = schl.GetType().GetProperty("Emp").GetValue(schl, null)
var empName = emp.GetType().GetProperty("Name").GetValue(emp, null);
Split it up, get the Employee object and then get the Name of the Employee.
Although I don't see the benefit for this in this instance when you can do string empName = schl.Employee.Name - unless the scope of the code is different?
Suppose I have a List of Person (which is a class). It contains about 20 field (Name, Surname, Age, DateOfBirthdate, and so on). So I got this list:
var listOfPersons= MyContext.Persons.Cast<Person>();
Now, I need to iterate through this List, and for each Person adding a new field (which it is not present in the class), called, let's say, CurrentDateTime.
I could create a new object, with the new field, and "copy & paste" values from Person to the new Class. Somethings like:
PersonNew newPerson = new PersonNew("Name", "Surname", "Age", "DateOfBirthdate", ... "CurrentDateTime");
But this is very bad if in the future I change the Person class. So, is there a strategy to "extending Person" with a new field? That takes the Person instance (whatever it is) and adds the new field?
You can create some static method that create PersonNew from Person using Automapper.
public class PersonNew : Person
{
public static PersonNew CreateFromPerson(Person person, DateTime currentDateTime)
{
var newPerson = Mapper.Map<PersonNew>(person);
newPerson.CurrentDateTime = currentDateTime;
}
}
I think that the solution you described works fine. If you want to keep track of each person's birthday without extending the Person class, you might use a Dictionary object
var listOfPersons = MyContext.Perons.Cast<Person>();
Dictionary<Person, DateTime> birthdays = new Dictionary<Person, DateTime>
foreach(Person person in listOfPersons)
{
birthdays.Add(person, getBirthday(person);
}
One solution is to make your class partial, and add your field in another partial definition of your class:
public partial class Person
{
public string Name { get; set; }
public string FirstName { get; set; }
...
}
...
public partial class Person
{
public DateTime CurrentDateTime { get; set; }
}
...
var listOfPersons = MyContext.Persons.Cast<Person>();
foreach (var person in listOfPersons)
{
person.CurrentDateTime = ....
}
Do note that you will use the same instance of your class.
First I would suggest using extension methods for projecting collections instead of iterating. Like that:
var newCollection = oldCollection.Select(entity => MakeNewType(entity))
Second, it's not completely clear what you mean by "extending Person" with a new field. Here are the couple of ways you can accomplish that.
1) Make another class with the new field and map it to the old one. This is a common scenario for asp.net mvc application where you map models to the appropriate viewmodels. Automapper is useful for these types of scenario (see SÅ‚awomir Rosiek anwser)
2) Take advantage of dlr in c# 4+. Yuo will lose the intellisense for dynamic objects, but they canned be passed around functions
var newPeople = people.Select(p =>
{
dynamic expando = new ExpandoObject();
expando.Id = p.Id;
expando.FirtName = p.FirtName;
/* ... */
expando.CurrentDateTime = DateTime.Now;
return expando;
});
3) Use Anonymous types. Anonymous types cannot be passed to another functions, so this approach is useful when you need to quickly project data inside a single method and calculate some result
var newPeople = people.Select(p => new
{
Id = p.Id,
FirtName = p.FirtName,
/* ... */
CurrentDateTime = DateTime.Now
});
in both cases you can now access newly "created" property:
foreach(var p in newPeople)
{
Console.WriteLine("CurrentDateTime: {0}", p.CurrentDateTime);
}
4) If you really need to create a fully featured .net class at runtime you can use Reflection.Emit. This scenario is typically used to create dynamic proxies - subclasses which implement some functionality only known at runtime. Entity framework does this.
I am trying to get into LINQ to objects as I can see the power of it. Lucky enough I have a question that I think LINQ should be able to solve.
Here is the question (the details are an example);
public class SchoolClass
{
public int ID;
public string Name;
public string Teacher;
public string RoomName;
public string Student_Name;
public int Student_Age;
}
As you can see by the example, there is a one to many relationship between the ClassName, Teacher and Room and the Students, i.e. there are potentially many students in the one class.
If we have a List is it possible using LINQ to create a List but have only one instance ID, Name, Teacher, RoomName and an ArrayList of Student_Name and Age?
Producing this:
public class Students
{
public string Student_Name;
public int Student_Age;
}
public class SchoolClass
{
public int ID;
public string Name;
public string Teacher;
public string RoomName;
public ArrayList Students;
}
Essentially, using LINQ to clean the List to a more logical structure?
To give some background to this example. The second structure is used by a DataGrid to produce a Master-Child relationship. We store SchoolClass and StudentInformation in classes as shown above. It would be good use of LINQ to be able to convert our initial List into a structure which can be used by the DataGrid.
I changed the ArrayList to List<Students>, and:
List<SourceData> source = new List<SourceData>();
//...your data here ;-p
var classes = (from row in source
group row by new {
row.ID, row.Name,
row.Teacher, row.RoomName }
into grp
select new SchoolClass
{
ID = grp.Key.ID,
Name = grp.Key.Name,
Teacher = grp.Key.Teacher,
RoomName = grp.Key.RoomName,
Students = new List<Students>(
from row in grp
select new Students
{
Student_Age = row.Student_Age,
Student_Name = row.Student_Name
})
}).ToList();
If I'm understanding this correctly, I would've thought the best way to implement the SchoolClass class would be to create a Student class (probably a LINQ-to-SQL entity, if you're using it) and to have a generic list of type student, something similar to this:
public class SchoolClass
{
public int ID;
public string Name;
public string Teacher;
public string RoomName;
public List<Student> Students;
}
The list of students could then be populated using a linq query, although I'm not sure exactly how without more information.
Hope this is some help.