Here is my person class:
public class Person
{
public string Name;
public string LastName;
public int Age;
public Person()
{
}
public Person(string name, string lastName, int age)
{
Name = name;
LastName = lastName;
Age = age;
}
}
Here is my main program. The current output is ListDemo.Person. ListDemo is my solution name and Person is my class name. How can I get the all details of a person in an output?
class Program
{
static void Main(string[] args)
{
List<Person> personList = new List<Person>();
personList.Add(new Person { Name = "Ahmad", LastName = "Ashfaq", Age = 20 });
personList.Add(new Person { Name = "Ali", LastName = "Murtza", Age = 23 });
foreach (Person item in personList)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
This is pretty simple.
public class Person
{
public string Name;
public string LastName;
public int Age;
public Person()
{
}
public Person(string name, string lastName, int age)
{
Name = name;
LastName = lastName;
Age = age;
}
public override string ToString()
{
return string.Format("{0} {1} - {2} Years Old", Name, LastName, Age);
}
}
Which you can use exactly how you were in the original place:
foreach (Person item in personList)
{
Console.WriteLine(item);
}
Which will print out like:
Jane Doe - 23 Years Old
John Doe - 14 Years Old
Jim Doe - 120 Years Old
The .ToString() is inherited from Object and is available to override on every class you create. You can use it to return string data that represents the object. By default this just returns the type name ListDemo.Person as you found out, but if you override it, you can return whatever you want.
Edite your code to be like this
class Program
{
static void Main(string[] args)
{
List<Person> personList = new List<Person>();
personList.Add(new Person { Name = "Ahmad", LastName = "Ashfaq", Age = 20 });
personList.Add(new Person { Name = "Ali", LastName = "Murtza", Age = 23 });
foreach (Person item in personList)
{
Console.WriteLine(item.Name);
Console.WriteLine(item.LastName);
Console.WriteLine(item.Age);
}
Console.ReadKey();
}
}
Console.WriteLine("Name = {0}, Last Name = {1}, Age = {2}", item.Name, item.LastName, item.Age);
That will output the data you are looking for by going through the properties in the items and giving you the output you desire.
Likewise, if you are looking for default behavior of generating a string from your class, you can override the ToString() method for your class to give the output you desire.
public override string ToString()
{
return string.Format("Name = {0}, Last Name = {1}, Age = {2}", Name, LastName, Age);
}
You have to override te ToString method in your Person class. The result of that function is what's printed. Insert the following code into your Person class:
public override string ToString() {
return string.Format("Name: {0}, LastName: {1}, Age: {2}", Name, LastName, Age);
}
Alternatively, if you do not want the string representation of your class to change. You could print the string generated with the above code instead of printing the object itself.
Beside of using ToString() method that is useful to output single value i am surprised that no one mentioned that you can create custom extension method for IEnumerable<T> (interface that is implemented by List<T>) to print all your values :
public static class Helper
{
public static void Print(this IEnumerable<Person> people)
{
foreach(Person p in people)
Console.WriteLine(string.Format("Name : {0}, Last Name : {1}, Age : {2}", p.Name, p.LastName, p.Age));
}
}
And use it in a way like if it was defined in List<T> :
class Program
{
static void Main(string[] args)
{
List<Person> personList = new List<Person>();
personList.Add(new Person { Name = "Ahmad", LastName = "Ashfaq", Age = 20 });
personList.Add(new Person { Name = "Ali", LastName = "Murtza", Age = 23 });
personList.Print();
}
}
Related
The code is for taking the input from user such as their name and date of birth and return details as name and their age and whether they are child or not
Apart from the Adult property the rest of the code works fine
using System;
using System.IO;
public class Person
{
//Fill code here
private string firstName;
private string lastName;
private DateTime dob;
//private string adult;
public string FirstName
{
set { firstName = value; }
get { return firstName; }
}
public string LastName
{
set { lastName = value; }
get { return lastName; }
}
public DateTime Dob
{
set { dob = value; }
get { return dob; }
}
}
In the below property it has to check age and return "Adult" if the age is above or equal to 18 else "Child".
And according to the question i cannot declare the field for this.
public string Adult
{
get
{
return Adult;
throw (stackoverflow)
}
set
{
if (GetAge(dob) >= 18)
{
Adult = "Adult";
}
else
{
Adult = "Child";
}
}
}
Help me with the corrections needed for the above property so that it does not throw any exceptions and the reason why it throws the exception
public void DisplayDetails()
{
Console.WriteLine("First Name: {0}", firstName);
Console.WriteLine("Last Name: {0}", lastName);
int age = GetAge(dob);
Console.WriteLine("Age: {0}",age);
Console.WriteLine(Adult);
}
public int GetAge(DateTime dob)
{
int age = 0;
age = DateTime.Now.Year - dob.Year;
return age;
}
}
public class Program
{
public static void Main(String[] args)
{
//Fill code here
Person p = new Person();
Console.WriteLine("Enter first name");
p.FirstName = Console.ReadLine();
Console.WriteLine("Enter last name");
p.LastName = Console.ReadLine();
Console.WriteLine("Enter date of birth in yyyy/mm/dd/ format");
p.Dob = Convert.ToDateTime(Console.ReadLine());
p.DisplayDetails();
}
}
You have an Adult property, and inside that property you manually defined a getter and setter, but they both use exactly the same property instead of using a field like you do in your other properties.
Note that the fields used in your other properties have lowercase names, while the properties start with an Upper case letter (which means that they are separate entities).
So you did declare adult like this but have commented it out:
//private string adult;
So you need to first uncomment it, then use it in your getter & setter.
public string Adult
{
get
{
return adult;
}
set
{
if (GetAge(dob) >= 18)
{
adult = "Adult";
}
else
{
adult = "Child";
}
}
}
But this also doesn't make sense, as your setter is not using the value which you pass into it! So while this might work, it is not really the best way to do it. Instead just use the Getter to return if it is an adult or child each time.
public string Adult
{
get
{
if (GetAge(dob) >= 18)
return "Adult";
else
return "Child";
}
}
(You should also include handling in case dob value is not valid (e.g. default value)
BTW: It might be better to use an Enum rather than a string, or just a boolean indicating if it is an adult (true) or child (false).
i'm very new to programming and in the progress of learning.
here is my code
namespace ConsoleApp9
{
class Program
{
static void Main(string[] args)
{
Person p = new Person("john", "doe", tittles:null);
Person td = new Person("tom","jones");
Person w = new Person();
Console.WriteLine(td);
Console.WriteLine(p.SayHello("vahid"));
var str = p.SayHello("nick");
Console.WriteLine(str);
p.DoSome();
var m = w.Tittles[0];
Console.WriteLine(m);
}
}
public class Person
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
private string[] tittles = new string[6] {
"Mr","Mrs", "Miss","Sir", "Doctor","Sister"
};
public string[] Tittles
{
get { return tittles; }
set { tittles = value; }
}
public Person()
{
}
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public Person(string firstName, string lastName, string[] tittles )
{
FirstName = firstName;
LastName = lastName;
Tittles = tittles;
}
public override string ToString()
{
return "Welcome to C# " + Tittles[0] + " " + FirstName + " " + LastName;
}
public string SayHello(string name)
{
return "hello " + name;
}
public void DoSome()
{
Console.WriteLine(FirstName + " "+ LastName + " this is a void method.");
}
}
}
my question is how to give other value than null in Person p = new Person("john", "doe", tittles:null);
tittles is my string array
i tried tittles[1] forexample but end up with an error.
is there a way this could be done?
thanks
Here's one way to do it:
Person p = new Person("john", "doe", new string[] { "one", "two" });
Or, you could use the params keyword to define a constructor that takes any number of strings:
public Person(string firstName, string lastName, params string[] tittles)
{
FirstName = firstName;
LastName = lastName;
Tittles = tittles;
}
Then you can create Person objects with any number of titles without having to create a temporary string array:
Person p = new Person("john", "doe", "one", "two");
Person j = new Person("jane", "doe", "one", "two", "three");
Person td = new Person("tom", "jones", "mr");
If you are instantiating your class with the constructor that take 3 arguments you will override the private field array titles in your class. I am assuming that you want to keep the values in there and therefore you should instantiate the class with the constructor that takes 2 arguments as that does not touch the Titles property
Person p = new Person("John", "Doe");
When instantiating with 3 args provide an array of strings like this:
Person p = new Person ("John", "Doe", new string[]{"title1", "title2"})
I created 3 objects of a class and I want to display on the console how many objects I have created (using a static class variable) - How do I do this ?
I put public static int count = 0; in the class I created but I couldn't get it to increment (count++;) based on how many objects I created of the class. I created the 3 objects in the main method and gave them values for variables.
here is the class I created in my program :
public class Student
{
public static int count = 0;
// count++;
private string firstName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
private string lastName;
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
private string birthDate;
public string BirthDate
{
get { return birthDate; }
set { birthDate = value; }
}
}
In the main method I created 3 objects of class Student:
static void Main(string[] args)
{
// Create 3 students
Student student1 = new Student
{
FirstName = "John",
LastName = "Wayne",
BirthDate = "26/05/1907"
};
Student student2 = new Student
{
FirstName = "Craig",
LastName = "Playstead",
BirthDate ="01/01/1967"
};
Student student3 = new Student
{
FirstName = "Paula",
LastName = "Smith",
BirthDate = "01/12/1977"
};
// Console.WriteLine("The course contains {1} students(s) " studentCounter );
I can't get the counter to ++ based on the way I created the objects.
Increment the count in the constructor:
public class Student
{
public static int count = 0;
public Student()
{
// Thread safe since this is a static property
Interlocked.Increment(ref count);
}
// use properties!
public string FirstName { get; set; }
public string LastName { get; set; }
public string BirthDate { get; set; }
}
You just need a constructor, there you can increment the count.
public Student()
{
count++;
}
You can increment the counter in the constructor
public Student()
{
count++;
}
To print the count variable
we should write some code like below
public static int GetCount()
{
return count;
}
and main class look like :
static void Main(string[] args)
{
// Create 3 students
Student student1 = new Student
{
FirstName = "John",
LastName = "Wayne",
BirthDate = "26/05/1907"
};
Student student2 = new Student
{
FirstName = "Craig",
LastName = "Playstead",
BirthDate ="01/01/1967"
};
Student student3 = new Student
{
FirstName = "Paula",
LastName = "Smith",
BirthDate = "01/12/1977"
};
//To print the count
Console.WriteLine(" Number of Objects is : "+Student.GetCount());
}
and if we have parameterized constructor then we also have to write count++ in that constructor.
I want to get the difference between two integers, in this case "Age" - subtract them.
Here my class and my list. I want to, with a method, take the age from Robin and Sara and show the age difference. Is this possible with LINQ or..?
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
public class LinqQuery
{
private readonly List<Person> _persons = new List<Person>
{
new Person {FirstName = "Robin", LastName = "Blixt", Age = 29},
new Person {FirstName = "Sara", LastName = "Johansson", Age = 44}
};
public IEnumerable<Person> GetAll()
{
return _persons;
}
public void difference()
{
?????
Console.ReadKey();
}
}
Thanks in advance.
You can use lambda expression to find specified index if FirstName is youre key and you have more items than two.
Please note that I did not check any erros (empty list etc.)
public void diff()
{
int indxRobin = lst.FindIndex((item) => { return item.FirstName == "Robin"});
int indxSara = lst.FindIndex((item) => { return item.FirstName == "Sara"});
return lst[indxRobin].Age - lst[indxSara].Age;
}
Using a cross-join you could calculate the age difference for all permutations in the list.
Of course, this is very crude and gives all duplicates, but it's easy from there to remove the duplicates in the query.
public void Difference()
{
var ageDifferences = from p1 in _persons
from p2 in _persons
select new
{
P1FullName = p1.FirstName + " " + p1.LastName,
P2FullName = p2.FirstName + " " + p2.LastName,
AgeDifference = Math.Abs(p1.Age - p2.Age)
};
foreach (var item in ageDifferences)
{
Console.Out.WriteLine("{0} and {1} have {2} years of age difference.", item.P1FullName, item.P2FullName, item.AgeDifference);
}
Console.ReadKey();
}
Thanks, #Tim Schmelter for the suggestion :)
public void difference()
{
int sara= _persons.FirstOrDefault(p=>p.FirstName=="Sara").Age;
int robin=_persons.FirstOrDefault(p=>p.FirstName=="Robin").Age;
int difference= Math.abs(sara-robin);
Console.ReadKey();
}
I have a class of persons and list collection as list contains all the values of person class
such as :
List ilist has 2 values [0]={firstname,lastname} . [1]={firstname2,lastname2}
now when i am iterating into the list i am able to print the list but i want to change the value of some parts of my list e.g in index 1 if i want to change the value of firstname2 to firstname3 i am not able to do it . Can anyone tell me how to print the list and then on that index changing any value of the index , i.e. firstname and secondname variable in the person class so that i can update my values
Thanks
According to the docs on msdn you can use the familiar index operator (like on what you use on arrays). So myList[1].lastname = "new last name"; should do it for you.
Docs are here; http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx
Keep in mind you need to do bounds checking before access.
I came here whilst searching for access specific index in object array values C# on Google but instead came to this very confusing question. Now, for those that are looking for a similar solution (get a particular field of an object IList that contains arrays within it as well). Pretty much similar to what the OP explained in his question, you have IList person and person contains firstname, lastname, cell etc and you want to get the firstname of person 1. Here is how you can do it.
Assume we have
IList<object> myMainList = new List<object>();
myMainList.Add(new object[] { 1, "Person 1", "Last Name 1" });
myMainList.Add(new object[] { 2, "Person 2", "Last Name 2" });
At first, I though this would do the trick:
foreach (object person in myMainList)
{
string firstname = person[1].ToString() //trying to access index 1 - looks right at first doesn't it??
}
But surprise surprise, C# compiler complains about it
Cannot apply indexing with [] to an expression of type 'object'
Rookie mistake, but I was banging my head against the wall for a bit. Here is the proper code
foreach (object[] person in myMainList) //cast object[] NOT object
{
string firstname = person[1].ToString() //voila!! we have lift off :)
}
This is for any newbie like me that gets stuck using the same mistake. It happens to the best of us.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
List<Person> list = new List<Person>();
Person oPerson = new Person();
oPerson.Name = "Anshu";
oPerson.Age = 23;
oPerson.Address = " ballia";
list.Add(oPerson);
oPerson = new Person();
oPerson.Name = "Juhi";
oPerson.Age = 23;
oPerson.Address = "Delhi";
list.Add(oPerson);
oPerson = new Person();
oPerson.Name = "Sandeep";
oPerson.Age = 24;
oPerson.Address = " Delhi";
list.Add(oPerson);
int index = 1; // use for getting index basis value
for (int i=0; i<list.Count;i++)
{
Person values = list[i];
if (index == i)
{
Console.WriteLine(values.Name);
Console.WriteLine(values.Age);
Console.WriteLine(values.Address);
break;
}
}
Console.ReadKey();
}
}
class Person
{
string _name;
int _age;
string _address;
public String Name
{
get
{
return _name;
}
set
{
this._name = value;
}
}
public int Age
{
get
{
return _age;
}
set
{
this._age = value;
}
}
public String Address
{
get
{
return _address;
}
set
{
this._address = value;
}
}
}
}
More information on your requirement / why you are accessing the list this way might help provide a better recommendation on approach but:
If you want to use your list in this way frequently an Array or ArrayList may be a better option.
That said, if your specific issue is determining the current element you want to change's ID you can use IndexOf(). (note this will loop the array to find the object's position)
If you just know the index of the element, you can reference as both you and #evanmcdonnal describe.
Lists can be modified directly using their indexer.
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
var list = new List<Person>
{
new Person
{
FirstName = "Bob",
LastName = "Carlson"
},
new Person
{
FirstName = "Elizabeth",
LastName = "Carlson"
},
};
// Directly
list[1].FirstName = "Liz";
// In a loop
foreach(var person in list)
{
if(person.FirstName == "Liz")
{
person.FirstName = "Lizzy";
}
}
I do not see where you can meet the problem:
public class Persons
{
public Persons(string first, string last)
{
this.firstName = first;
this.lastName = last;
}
public string firstName { set; get; }
public string lastName { set; get; }
}
...
List<Persons> lst = new List<Persons>();
lst.Add(new Persons("firstname", "lastname"));
lst.Add(new Persons("firstname2", "lastname2"));
for (int i = 0; i < lst.Count; i++)
{
Console.Write("{0}: {2}, {1}", i, lst[i].firstName, lst[i].lastName);
if (i == 1)
{
lst[i].firstName = "firstname3";
lst[i].lastName = "lastname3";
Console.Write(" --> {1}, {0}", lst[i].firstName, lst[i].lastName);
}
Console.WriteLine();
}
}
Output:
0: lastname, firstname
1: lastname2, firstname2 --> lastname3, firstname3