I have an interface:
public Interface IStudent
{
Students students {get;}
Boolean CanStayAfterHours;
}
public enum Students
{
Student1,
Student2,
Student3,
Student4
}
How can I add IStudent properties to a generic list? List<IStudent>?
You first need to have a class that implements that interface:
public class Student : IStudent {
Students students { get; set; } // set, for example
Boolean CanStayAfterHours { get; set; }
}
Then you can add them to a list like this:
var studentList = new List<IStudent>() {
new Student() { CanStayAfterHours = true },
new Student() { CanStayAfterHours = false, Students = Students.Student1 },
new Student() { CanStayAfterHours = true },
};
Your design doesn't make much sense... but I'll leave that to you to figure out.
IList<IStudent> can be used to keep a list of IStudent objects. Of course you need a class Student that implements IStudent, because you cannot create an instance of an interface. The purpose of your enum is unclear, you clearly don't want an enum value for each student, since that would require a rebuild of your application every time a new student signs up.
You'll need to implement a concrete object that implements the interface
public class ConcreteStudent : IStudent {
public Students students { get; set; }
public bool CanStayAfterHours { get; set; }
}
Some changes where required to the interface, I added some setters to the interface, hope this agrees with your design
public interface IStudent {
Students students { get; set; }
Boolean CanStayAfterHours { get; set; }
}
Then adding these objects to a list, we do the following
List<IStudent> students = new List<IStudent>()
students.Add(new ConcreteStudent()
{
students = Students.Student1,
});
interface ListofPatientService
{
List
retriev();
}
class listofServiceDummy : ListofPatientService
{
List<patientmodel> list = new List<patientmodel>
{
new patientmodel(){Name="Abdi", Age= 30, Description=""},
new patientmodel(){Name="HassaN", Age= 40, Description=""},
new patientmodel(){Name="Hasna", Age= 35, Description=""},
new patientmodel(){Name="Moktar", Age= 50, Description=""},
new patientmodel(){Name="Liban", Age= 55, Description=""},
};
}
Related
When joining multiple models, I can't access its properties in controller.
public class BirdModel
{
public IEnumerable<BirdFile> BirdFils { get; set; }
public IEnumerable<BirdFileDetail> BirdFileDetails { get; set; }
}
public partial class BirdFile
{
public int ID{ get; set; }
public string Name{ get; set; }
}
Is it possible to access like this
BirdModel b = new BirdModel();
b.BirdFile.ID
You problem with b.BirdFile.ID is that you are trying to access the property or a collection of objects that you have not initialised.
You need to create an instance of the encapsulating class, BirdModel then create an instance of your BirdFile collection and add values to it. From there you can get the specific "BirdFile" within your collection via iteration and then access its properties.
A small example below:
class Program
{
static void Main(string[] args)
{
var bm = new BirdModel();
bm.BirdFils = new List<BirdFile>
{
new BirdFile {ID = 1, Name = "Bird A"},
new BirdFile {ID = 2, Name = "Bird B"}
};
bm.BirdFils.ToList().ForEach(x => Console.WriteLine($"Name: {x.Name}, ID: {x.ID}"));
Console.ReadKey();
}
}
public class BirdModel
{
public IEnumerable<BirdFile> BirdFils { get; set; }
}
public partial class BirdFile
{
public int ID { get; set; }
public string Name { get; set; }
}
BirdModel contains a collection of BirdFile, so to access them you should write something like:
// create a new model
BirdModel b = new BirtdModel()
// create the instance of BirdFile list
b.BirdFils = new List<BirdFile>()
// add an item (just an example)
b.BirdFils.Add(new BirdFile{ ID = 1, Name = "Bird1"}
// Access to the previously created BirdFile
BirdFile bf = b.BirdFils[0]
I have four classes :
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Product> Product { get; set; }
}
public class Product
{
public int ProductNumber { get; set; }
public string ProductColor { get; set; }
}
///////////////////////////////////////////////
public class Customer_
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Article> Article { get; set; }
}
public class Article
{
public int ArticleNumber { get; set; }
public string ArticleColor { get; set; }
}
And one instance :
var Cus = new List<Customer>
{
new Customer()
{
FirstName = "FirstName1",
LastName = "LastName1",
Product = new List<Product>
{
new Product()
{
ProductColor = "ProductColor1",
ProductNumber = 11
}
}
},
new Customer()
{
FirstName = "FirstName2",
LastName = "LastName2",
Product = new List<Product>
{
new Product()
{
ProductColor = "ProductColor2",
ProductNumber = 12
}
}
}
};
I want to create a new object List<Customer_> with the value of my instance Cus. For example Customer.FirstName = Customer_.FirstName, Customer.Product.ProductColor = Customer_.Article.ArticleColor etc
What is the best way to do this easily, could one use a Dictionary?
Mapping can be accomplished through the use of an Interface.
Define an interface(s) which provide a mapping of logically named properties such as the common color properties you mention:
// Some entities have different named properties but can be joined
// using those properties. This interface shows a common color which
// when implemented will route the processing to a common shared property
// which reports and sets the associated color.
public interface IDefinedColor
{
string Color { get; set; }
}
If you have to create partial classes for Product and Article and have them adhere to said interfaces. Hint if using an entity mapper such as EF this is a great way to do such maping using partials. Implement implement the interface and hook up the commonality:
// Holds the common properties for future processing.
public partial class Product : IDefinedColor
{
public string Color
{
get { return ProductColor; }
set { ProductColor = value; }
}
}
Then work off of the IDefinedColor mapped implementations as needed.
By using interfaces one is letting all future developers know of the contract which specifies a business logic equality in the properties and it is not hidden in other joining classes.
You could create a mapper extension class
public static class MapperExtension
{
public Customer_ Convert(this Customer customer)
{
return new Customer_()
{
FirstName = customer.FirstName,
LastName = customer.LastName,
Article = customer.Product.Convert()
};
}
public static List<Article> Convert(this List<Product> products)
{
return products.Select(x=> new Article(){
ArticleNumber = x.ProductNumber,
ArticleColor = x.ProductColor
};
}
}
make sure you reference the proper namespace where you place the extension class.
Call the code like this
Where customers is a List filled from your code
List<Customer_> convertedCustomers_ = customers.Select(x=> x.Convert()).ToList();
It depends on the relationhip between those components but I would simply add constructor to Customer_ that accepts a Customer object. And then you invoke that do perform the conversion. e.g.
public class Article
{
public Article(Product source)
{
this.ArticleNumber = source.ProductNumber;
this.ArticleColor = source.ProductColor;
}
}
public class Customer_
{
public Customer_(Customer source)
{
this.FirstName = source.FirstName;
this.LastName = source.LastName;
this.Article = source.Product.Select(o => new Article(o)).ToList()
}
...
}
//and finally to convert the list you can do something like
//initial list
var Cus = new List<Customer>() { ... etc. }
/converted list
var Cus_ = Cus.Select(o => new Cusomter_(o)).ToList();
Edit: I see from your comment above that you actually have 100 properties to map. I can see this is a pain. But if you have complex transformations like Product to Article then I would still go the manual route as above so you can be completely clear about what is going on. Alternatively you could look to use inheritance to redesign your objects with common base classes or interfaces, that would probably make mapping easier.
a simple question about DTO, I have a DTO class Cars, and some others subclasses of cars models inside it.
public class Cars
{
public Ferrari FerrariModel { get; set; }
public Porshe PorsheModel {get; set; }
public Mustang MustangModel { get; set; }
}
public class Ferrari
{
public string collor{ get; set; }
public int year{ get; set; }
public double price{ get; set; }
}
and Porshe and Mustang are exactly the same Ferrari. The problem is I do not know how to proceed now. I try something like that
Cars cars = new Cars();
FerrariModel fm = new FerrariModel();
cars.FerrariModel.collor = txtCollor.Text;
And it is not working, as I get the follow error in the cars.FerrariModel.collor -> "Object reference not set paragraph An Instance of hum object . the hum object declaration".
I must confess I dont even know it "is possible" or if I am "inventing prograiming", so any help woulb be greatfull.
why use only a single class? Because a need to pass a single DTO in parameters: save(Cars car); update(Cars car)
using a second separeted class would force me to "overload" the method: save(Cars car); save(Ferrari ferrari);
if I use a single class (without Ferrari, Porshe and Mustang) the program work but I have lots of variables in my InteliSense, over 50.
Thank you.
You need to assign your fm instance to your Cars.FerarriModel property.
Cars cars = new Cars();
FerrariModel fm = new FerrariModel();
cars.FerrariModel = fm;
cars.FerrariModel.collor = txtCollor.Text;
Or even just:
Cars cars = new Cars();
cars.FerrariModel = new FerrariModel() { collor = txtCollor.Text };
I'm studying C# Classes and am trying to create a program that has a Class called Employee and derived classes of ProductionWorker, ShiftSupervisor, and TeamLeader.
I have a list box where I want to display All the employees, and within the program, there's functionality to add, edit, or remove respective people, but rather than making 3 lists like so:
List<ProductionWorkers> pWorkers = new List<ProductionWorkers>();
List<ShiftSupervisor> sSupervisors = new List<ShiftSupervisor>();
List<TeamLeader> tLeaders = new List<TeamLeader>();
I'd like to be able to have the Employee base class have or contain some sort of list of it's derived classes and their objects.
For example I'd like to be able to be able to Add and Remove derived objects to a list of Employees in some fashion, given the following example:
List<Employee> employees = new List<Employee>();
ProductionWorker _pWorker = new ProductionWorker();
_pWorker.Name = "Bob";
_pWorker.EmployeeID = 1234;
employees.Add(_pWorker));
I don't know if that's even possible or realistic to do that, but it would seem maybe there is a way from what I've read, I'm just not sure how to implement it. I'm open to better suggestions however, if someone knows of a better or proper way to get all the Employees listed into a ListBox without having to cycle through 3 different lists of the different derived classes.
For clarity, below is the Base class, then its following derived classes.
public class Employee
{
public string Name { get; set; }
public int EmployeeNumber { get; set; }
}
class ProductionWorker : Employee
{
public int ShiftNumber { get; set; }
public decimal HourlyPayRate { get; set; }
}
class TeamLeader : ProductionWorker
{
public int ReqHours { get; set; }
public int AttendedHours { get; set; }
}
class ShiftSupervisor : Employee
{
public int Salary { get; set; }
public int AnnualProductionBonus { get; set; }
}
I didn't realize until I posted my classes here that Team Leader is actually a derived class of Production Worker. I'm not sure if that changes things...
Yes, you can add Employee items and items deriving from Employee to the employees list.
List<Employee> employees = new List<Employee>();
ProductionWorker pWorker = new ProductionWorker {
Name = "Bob",
EmployeeID = 1234
};
employees.Add(pWorker);
If you want to display all these different kinds of employees in the same listbox, override the ToString method in these classes. The ListBox will automatically use it in order to display the items.
public class ProductionWorker : Employee
{
public override string ToString()
{
return String.Format("{0} ({1}), production", Name, EmployeeID);
}
}
You can assign the list of employees to the listbox like this
employeeListBox.DataSource = employees;
From the employees list you can access the members declared in Employee directly:
int id = employees[i].EmployeeID;
However; you need to cast, if you want to access members of derived types
int salary = 0;
var supervisor = employees[i] as ShiftSupervisor;
if (supervisor != null) {
salary = supervisor.Salary;
}
If you know the type of an item in advance you can cast directly
int salary = ((ShiftSupervisor)employees[0]).Salary;
List<Student> liStudent = new List<Student>
{
new Student
{
Name="Mohan",ID=1
},
new Student
{
Name="Ravi",ID=2
}
};
public class Student
{
public string Name { get; set; }
public int ID { get; set; }
}
Is there other way to write this? I am a newbie. I want to make instance of student class first and assign properties in list.
List<Student> liStudent = new List<Student>
{
new Student("Mohan",1),
new Student("Ravi",2)
};
public class Student
{
public Student(string name,int id)
{
Name=name;
ID=id;
}
public string Name { get; set; }
public int ID { get; set; }
}
Since Student is a reference type, you can indeed add the instances to the list first, and set their parameters afterwards:
List<Student> lst = new List<Student> { new Student(), new Student() };
lst[0].Name = "Mohan";
lst[0].ID = 1;
lst[1].Name = "Ravi";
lst[1].ID = 2;
It is going to work as you've written in Visual Studio 2008 and 2010. This way you use object initializer, there is no need to invoke a constructor. Read more on How to: Initialize Objects without Calling a Constructor (C# Programming Guide).