How to set mulitple records in constructor - c#

I'm not using this in a real app but I was just curious on how to do this (C#).
I set one record of sample data in the constructor :
public class MikesClass
{
public MikesClass()
{
Id = 01; Name = "Mike";
}
public int Id { get; set; }
public string Name { get; set; }
}
but I'm confused on how to set another record in it :
public MikesClass()
{
Id = 01; Name = "Mike";
Id = 02; Name = "Tom"; ???
}
If possible to do this, what is the syntax? thanks

You completely misunderstood what a constructor is. A constructor is for one single object. It creates one single object. Thus you cannot set another record with it. That record will be a different object. You just set the values as arguments to constructor when you create another record.
So, should at least be like this -
public class MikesClass
{
public MikesClass(int id, string name)
{
Id = id;
Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
}
and in some distance place when creating multiple records/objects -
var m1 = new MikesClass(0,"name1");
var m2 = new MikesClass(1, "name2");

Using the code you specified above, each time you write:
MikesClass mc = new MikesClass();
you will get an object of type MikesClass with the Id property set to 1 and the Name property set to "Mike". Since each instance of MikesClass represents a single object, you cannot have multiple objects represented within it.
What you can do though, is modify your constructor to take the two values as parameters. Like this:
public MikesClass(int id, string name)
{
Id = id;
Name = name;
}
You can then use this code to create multiple MikesClass objects like so:
MikesClass mike = new MikesClass(1, "Mike");
MikesClass tom = new MikesClass(2, "Tom");
Hope this makes sense.

What you're showing is a constructor. It is run when you create an instance of the MikeClass class.
What you want is to create several instances. Maybe in an array?
MikeClass[] array = new MikeClass[2];
MikeClass mc = new MikeClass(); /first instance
mc.Id = 1;
mc.Name = "Mike";
array[0] = mc;
mc = new MikeClass(); //another instance
mc.Id = 2;
mc.Name = "Tom";
array[1] = mc;
};
This is using object initializer syntax:
MikeClass[] array = new MikeClass[] {
new MikeClass { Id = 1, Name = "Mike" }, //first instance
new MikeClass { Id = 2, Name = "Tom" } //another instance
};
You can also create a constructor for the MikeClass class that takes parameters:
public MikeClass(int id, string name) {
Id = id;
Name = name;
}
Then:
MikeClass[] array = new MikeClass[] {
new MikeClass(1, "Mike"),
new MikeClass(2, "Tom")
};

Related

List Collection Class

Hello let me describe i don't have any errors in my code , i am just asking a very basic question here RELATED TO list collection class let see i have a class called customer
class customer
{
public int Id { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
}
in my main method i created an array of customer and initialize those properties that is present in my customer class
static void Main(string[] args)
{
customer[] customers = new customer[3];
customers[0] = new customer
{
Id = 1,
Name = "A",
Salary = 30000
};
customers[1]=new customer
{
Id = 2,
Name = " B",
Salary = 50000
};
customers[2] = new customer
{
Id = 3,
Name = "C",
Salary = 90000
};
List<customer> Cust= new List<customer>(2);
Cust.Add(customers[0]);
Cust.Add(customers[1]);
Cust.Add(customers[2]);
for (int i = 0; i < Cust.Count; i++)
{
customer C = Cust[i];
Console.WriteLine("Id = {0} & Name = {1} & Salary = {2}",C.Id,C.Name,C.Salary);
}
Console.ReadLine();
}
Okay! so this code is working so perfectly nice , but my question is that at last we created a list called cust and add all the custemers in to it , so why is it necessary to make another object with type customer as i did in for loop
customer C = Cust[i];
why can i don't call my code like this
console.WriteLine{Cust[i]}
As far as i know when we create object of the class than we can easily acces the code inside that class with that instance variable . so why not here?
In your for loop, you're not creating a new customer, you're just creating a reference to the existing one:
for (int i = 0; i < Cust.Count; i++)
{
customer C = Cust[i]; //<- not new, just a reference to the customer at index
Console.WriteLine("Id = {0} & Name = {1} & Salary = {2}",C.Id,C.Name,C.Salary);
}
A more concise way to loop is to use foreach instead of for (NOTE: using C# 6.0 string interpolation):
foreach(var c in Cust)
Console.WriteLine($"Id = {c.Id} & Name = {c.Name} & Salary = {c.Salary}");
To do what you were asking to do, you would first need to override the ToString() method on your class. The ToString() method will be called implicitly by Console.WriteLine:
class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
public override string ToString()
{
return string.Format("Id = {0} & Name = {1} & Salary = {2}", Id, Name, Salary);
}
}
Now that you have a default way to represent a customer as a string, you can do exactly what you were asking to do:
for (int i = 0; i < Cust.Count; i++)
{
Console.WriteLine(Cust[i]);
}
And, now that you have this, you can do it in an even easier way. The following will implicitly pass each item to Console.WriteLine(), which will call the item's ToString() method:
customers.ForEach(Console.WriteLine);
If for some reason you DON'T want to override the ToString method, you can still access the instance properties using the index without creating a new object, like so:
for (int i = 0; i < Cust.Count; i++)
{
Console.WriteLine("Id = {0} & Name = {1} & Salary = {2}",
Cust[i].Id, Cust[i].Name, Cust[i].Salary);
}

Linq select a single field using a string containing the name of the field

Let's say I have a simple list of objects like this:
public class DataField
{
public int DataFieldId {get; set;}
public int KeyId {get; set;}
public string FieldName {get; set;}
public string Data {get; set;}
}
Now I would like to get a list of the values in a Property using the string value of the Property name, like this:
public List<string> getFieldData(List<DataField> dataToSearch, string propertyName)
{
// This is the area I'd like to figure out.
return dataToSearch.Select(ds => ds.propertyName).Distinct.ToList();
}
public void MyMethod()
{
var data = new List<DataField>{
new DataField{DataFieldId = 1, KeyId = 1,
FieldName = "UserName", Data = "jSmith"},
new DataField{DataFieldId = 2, KeyId = 1,
FieldName = "Email", Data = "jSmith#nowhere.com"},
new DataField{DataFieldId = 3, KeyId = 1,
FieldName = "PreferredContact", Data = "Phone"},
new DataField{DataFieldId = 4, KeyId = 2,
FieldName = "UserName", Data = "jDoe"},
new DataField{DataFieldId = 5,KeyId = 2,
FieldName = "Email", Data = "janeDoe#emailServer.net"},
new DataField{DataFieldId = 6, KeyId = 2,
FieldName = "PreferredContact", Data = "Email"}
};
// Notice I want to search using a string
var fieldNames = getFieldData(data, "FieldName");
}
I would want fieldNames to be a List<string> containing:
"UserName"
"Email"
"PreferredContact"
I would like to use a string to specify the column to return.
You can use reflection. You're using "field" but the class actually contains properties, so use reflection's GetProperty() method. If you use fields instead, use GetField()
public static List<string> getFieldData(List<DataField> dataToSearch, string fieldName)
{
// You can use reflection to get information from types at runtime.
// The property_info variable will hold various data about the field
// name you pass in (type, name, etc)
var property_info = typeof(DataField).GetProperty(fieldName);
// We can then call property_info's GetValue() on an instantiated
// object of our class, and it will return the value of that property on that object
return dataToSearch.Select(ds => Convert.ToString(property_info.GetValue(ds))).Distinct().ToList();
}
PropertyInfo class: https://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo(v=vs.110).aspx
Type class: https://msdn.microsoft.com/en-us/library/system.type(v=vs.110).aspx

Storing Class Data In A List

Well I have a class like this and I want to store in a list which is defined as a static variable. I was following the reference here: Storing data into list with class
public class Faculty
{
public string Name { get; set; }
public string Dept { get; set; }
public string[] subInterest = new string[4];
}
However when I try to initialize the list as follows I have problem with the array part: Invalid initializer member declarator
SaveDirectory.list_of_faculty.Add(
new Faculty
{
Name = txtTeachherName.Text,
Dept = cmbDepts.Items.CurrentItem.ToString(),
subInterest[0] = "HELLO"
});
What am I doing wrong?
You can't reach in to your object and initialize members of an array that it holds using initializer syntax. You could work around this as follows:
var fac = new Faculty {
Name = txtTeachherName.Text,
Dept = cmbDepts.Items.CurrentItem.ToString(),
subInterest = new []{"HELLO", null, null, null}}
or after initialization:
fac.subInterest[0] = "HELLO";
The problem is due to:
subInterest[0] = "HELLO"
You can not partially initialize an array in Object Initializer, either it is full or nothing, You can do:
subInterest = new string[]{"HELLO"}
But, this will leave the array subInterest with size 1, not as size 4, as you have defined in your class. To get the array of same size you can do:
subInterest = new string[]{"HELLO",null,null,null}
Another option is to use List<string> instead of an Array. You can initialize it with value and later you can add items to it.
Modify your class like:
public class Faculty
{
public string Name { get; set; }
public string Dept { get; set; }
public List<string> subInterest;
}
and then:
new Faculty
{
Name = txtTeachherName.Text,
Dept = cmbDepts.Items.CurrentItem.ToString(),
subInterest = new List<string>(){"HELLO"}
};
Using a constructor can also solve the problem like
public class Faculty
{
public string Name { get; set; }
public string Dept { get; set; }
public string[] subInterest = new string[4];
public Faculty(string name, string dept, string[] si)
{
this.Name = name;
this.Dept = dept;
this.subInterest = si;
}
}
Then instantiate the faculty class
string[] subinterest = new string[]{"reading","swmming",null,null};
var fac = new Faculty("dgdfgdfgfg","dfgdgfgdfg", subinterest);

Mixing in new fields to an object without hard-coding its fields in a LINQ query?

I have a simple LINQ query here:
var Staffs = new[]
{
new { id = 1, name = "Jefferson", age = 42},
new { id = 2, name = "Jacobson", age = 54},
new { id = 3, name = "Zhang", age = 34}
};
var payroll = new[]
{
new { pid = 1, wage = 5000},
new { pid = 2, wage = 6500},
new { pid = 3, wage = 6700}
};
var q = from stf in Staffs
from pay in payroll
where stf.id == pay.pid
select new
{
stfObj = stf,
pay.pid,
pay.wage
};
Here, stfObj would be an object containing the id, name and age fields
Here comes the question:
Is it possible to turn the object into the fields themselves without explicitly hard-coding the field names like this:
select new
{
stf.id,
stf.name,
stf.age,
pay.pid,
pay.wage
};
In this way, there will be no need to change the select new block when I add a new field to Staffs, like Gender for example
Is that possible?
(ok, this looks like the question here... anyway, hoping to get better answers here)
Is this what you want!
select new
{
sId=stfObj.id,
sName=stfObj.name,
sAge=stdObj.age,
pId=pay.pid,
pWage=pay.wage
};
Why not simply embed your object ?
select new {
staff = stf,
pay = pay
};
I do not know, what you need this for. But you could try to use Dictionary<> for this. Say, we have a class:
public class Test
{
public string Name { get; set; }
public string Desc { get; set; }
}
So you can do the following:
List<Test> list = new List<Test>
{
new Test
{
Name = "Test 1",
Desc = "Desc 1"
}
};
var temp = list.Select(t =>
{
Dictionary<string, object> values = new Dictionary<string, object>();
foreach (PropertyInfo pi in t.GetType().GetProperties())
values[pi.Name] = pi.GetValue(t, null);
return values;
})
.FirstOrDefault();
temp.ToList().ForEach(p => Console.WriteLine(string.Format("{0}:\t{1}", p.Key, p.Value)));
So if you add a property to the Test class, say, like this:
public bool Extra { get; set; }
You'll get it in the dictionary automatically. Probably you'll have to work with reflection methods overloads to get exactly what you need...

Accessing a variable using a string containing the variable's name [duplicate]

This question already has answers here:
string to variable name
(4 answers)
Closed 9 years ago.
I am reading the name of a string variable from the database (e.g. "_datafile"). I want to know how I can access a named variable within my program using this string.
I have already tried using a dictionary, hash table, and a switch-case statement but I would like to have the variable resolve itself dynamically. Is this possible?
Do you mean you want to get the value of a field using the field name as a string?
public class MyClass
{
public string _datafile;
public MyClass()
{
_datafile = "Hello";
}
public void PrintField()
{
var result = this.GetType().GetField("_datafile").GetValue(this);
Console.WriteLine(result); // will print Hello
}
}
EDIT: #Rick, to respond to your comment:
public class MyClass
{
public IEnumerable<string> _parameters = new[] { "Val1", "Val2", "Val3" };
public void PrintField()
{
var parameters = this.GetType().GetField("_parameters").GetValue(this) as IEnumerable;
// Prints:
// Val1
// Val2
// Val3
foreach(var item in parameters)
{
Console.WriteLine(item);
}
}
}
If you want to get the value of a field based on its string name you will have to use reflection.
class MyClass
{
public int DataFile { get; set; }
public int _datafile;
}
var ob = new MyClass();
var typ = typeof(MyClass);
var f = typ.GetField("_datafile");
var prop = typ.GetProperty("DataFile");
var val = f.GetValue(ob);
var propVal = prop.GetValue(ob);
Usually you would create a class representing the values of one table record. If your table has an ID a FirstName and a LastName column, you would create a class like this
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Then you create a list of persons
var people = new List<Person>();
Now you can add persons to the list.
var p = new Person();
p.ID = 5;
p.FirstName = "John";
p.LastName = "Doe";
people.Add(p);
You can use a DataReader in order to read from a table
string sql = "SELECT * FROM tblPerson WHERE LastName LIKE #pattern";
cmd = new SqlCommand(sql);
cmd.Connection = "server=test;uid=sa;pwd=manager;database=northwind";
cmd.Parameters.AddWithValue("#pattern", "A%"); // Names beginning with "A"
using (SqlDataReader reader = cmd.ExecuteReader()) {
// Get column indexes
int idOrdinal = reader.GetOrdinal("ID");
int firstNameOrdinal = reader.GetOrdinal("FirstName");
int lastNameOrdinal = reader.GetOrdinal("LastName");
while(reader.Read()) {
var p = new Person();
p.ID = reader.GetInt32(idOrdinal);
p.FirstName = reader.GetString(firstNameOrdinal);
p.LastName = reader.GetString(lastNameOrdinal);
people.Add(p);
}
}

Categories

Resources