text
stringlengths
0
13.4k
{
new Model() {Name = "Item1", Selected = true},
new Model() {Name = "Item2", Selected = false},
new Model() {Name = "Item3", Selected = false},
new Model() {Name = "Item4"}
};
Here, we are creating several new instances of our Model class, and initializing them with data. What if we added a
constructor?
public class Model
{
public Model(string name, bool? selected = false)
{
Name = name;
selected = Selected;
}
public string Name { get; set; }
public bool? Selected { get; set; }
}
This allows us to initialize our List a little differently.
var SelectedEmployees = new List<Model>
{
new Model("Mark", true),
new Model("Alexis"),
new Model("")
};
What about a Class where one of the properties is a class itself?
public class Model
{
public string Name { get; set; }
public bool? Selected { get; set; }
}
public class ExtendedModel : Model
{
public ExtendedModel()
{
BaseModel = new Model();
}
public Model BaseModel { get; set; }
public DateTime BirthDate { get; set; }
}
Notice we reverted the constructor on the Model class to simplify the example a little bit.
var SelectedWithBirthDate = new List<ExtendedModel>
{
new ExtendedModel()
{
BaseModel = new Model { Name = "Mark", Selected = true},
BirthDate = new DateTime(2015, 11, 23)
GoalKicker.com – .NET Framework Notes for Professionals
21
},
new ExtendedModel()
{
BaseModel = new Model { Name = "Random"},
BirthDate = new DateTime(2015, 11, 23)
}
};
Note that we can interchange our List<ExtendedModel> with Collection<ExtendedModel>, ExtendedModel[],
object[], or even simply [].
Section 5.4: Queue
There is a collection in .Net used to manage values in a Queue that uses the FIFO (first-in first-out) concept. The
basics of queues is the method Enqueue(T item) which is used to add elements in the queue and Dequeue() which
is used to get the first element and remove it from the queue. The generic version can be used like the following
code for a queue of strings.
First, add the namespace:
using System.Collections.Generic;
and use it:
Queue<string> queue = new Queue<string>();
queue.Enqueue("John");
queue.Enqueue("Paul");
queue.Enqueue("George");
queue.Enqueue("Ringo");
string dequeueValue;
dequeueValue = queue.Dequeue(); // return John