Initializing a List c# - c#

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).

Related

Object’s Parent Current Instance

Having the following object(s):
public class Employee
{
public string LastName { get; set; } = "";
internal class SubordinateList<T> : List<T>, IPublicList<T> where T : Employee
{
public new void Add(T Subordinate) { }
}
public IPublicList<Employee> Subordinates = new SubordinateList<Employee>();
}
The SubordinateList object is inside the Employee object making Employee the parent of SubordinateList in a certain way.
If we put this code below:
Anakin = New Employee();
Luke = New Employee();
Anakin.Subordinates.Add(Luke);
The third line will trigger the method “Add” of SubordinateList.
I would like to get the Current Instance for the Parent of SubordinateList like this:
public new void Add(T Subordinate)
{
T Manager = Subordinate.ParentInstance;
// then it will be possible to see the current value of
// the property "LastName" for Anakin with "Manager.LastName"
}
You can't do it that way since you don't have a reference to the manager. This is how I would implement it:
public class Employee
{
public string FirstName { get; set; } = "";
public string LastName { get; set; } = "";
public string HiredDate { get; set; } = "";
private List<Employee> _subordinates = new List<Employee>();
public ReadOnlyCollection<Employee> Subordinates => _subordinates.AsReadOnly();
public void AddSubordinate(Employee employee)
{
_subordinates.Add(Employee);
//the manager is 'this'
var managerLastName = this.LastName;
}
}
Exposing the subordinate list as a ReadOnlyCollection allows other classes to read the list, but prevents them from updating the list directly. So only the AddSubordinate() method can be used to add employees, where you can do what you need with the manager's information.

How to access properties inside multiple model

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]

C# map two complex objects

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.

How can I create a list with Interface Instances

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=""},
};
}

Convert one set of objects to another set of objects of different class in single line. C#

I have 2 classes with different properties in each. Also I have a collection of one set of objects of the class A. Now I want to copy these to an array of objects of Class B.
The 2 classes are not inter related and also the fields are different in each. SO i have to explicitly map the fields i want to copy. Right now I am using a foreach to copy individual element. Is there a shorter way to accomplish this.
This is the class B
public class Event
{
public string EventOriginTime { get; set; }
public string EventReceivedTime { get; set; }
public int EventCode { get; set; }
public string CardNumber { get; set; }
public string ReaderName { get; set; }
}
First class A also will appear something like this but that is a 3rd party class.
Current solution I have is:
List<Event> listOfEvents = new List<Event>();
foreach (var eachEvent in eventsFromArgus)
{
listOfEvents.Add( new Event
{
ReaderName = eachEvent.DeviceName,
EventCode = eachEvent.EventCode,
EventReceivedTime = eachEvent.ReceiveTime.ToString(),
EventOriginTime = eachEvent.OriginTime.ToString(),
CardNumber = eachEvent.CredentialIdentifier
});
}
You could use LINQ:
List<event> listOfEvents =
(from eachEvent in eventsFromArgus
select new Event(
ReaderName = eachEvent.DeviceName,
EventCode = eachEvent.EventCode,
EventReceivedTime = eachEvent.ReceiveTime.ToString(),
EventOriginTime = eachEvent.OriginTime.ToString(),
CardNumber = eachEvent.CredentialIdentifier)).ToList();
But that's not terribly different from what you already have.
Or, you could look into something like AutoMapper.
Another approach is to pass the third party object directly into the Event class' constructor:
public class Event
{
private readonly ThirdPartyClass _eventFromArgus;
public Event(ThirdPartyClass eventFromArgus)
{
_eventFromArgus = eventFromArgus;
}
public string ReaderName { get { return _eventFromArgus.DeviceName; } }
// etc.
}
Then you can just do this:
var listOfEvents = eventsFromArgus.Select(eachEvent => new Event(eachEvent));
also with linq as Jim suggested but a bit different
var listOfEvents = eventsFromArgus.Select(eachEvent =>
new Event( ReaderName = eachEvent.DeviceName,
EventCode = eachEvent.EventCode,
EventReceivedTime = eachEvent.ReceiveTime.ToString(),
EventOriginTime = eachEvent.OriginTime.ToString(),
CardNumber = eachEvent.CredentialIdentifier)).ToList();
You could add a constructor to the Event class:
public Event(string EventOriginTime, string EventReceivedTime, int EventCode, string CardNumber, string ReaderName)
{
this.EventOriginTime = EventOriginTime;
this.EventReceivedTime = EventReceivedTime;
this.EventCode = EventCode;
this.CardNumber = CardNumber;
this.ReaderName = ReaderName;
}
Then at least you don't have to specify the field names when creating a new instance.
List<Event> listOfEvents = new List<Event>();
foreach (var eachEvent in eventsFromArgus)
{
listOfEvents.Add(new Event(eachEvent.OriginTime.ToString(), eachEvent.ReceiveTime.ToString(), eachEvent.EventCode, eachEvent.DeviceName)
}

Categories