- What is collection?
Data structure, used when we want to operate on group or set of data with vary length. - Table, list, loop foreach
A)Table – special kind of collection with const length
var array = new int[10]; //rozmiar tablicy: 10
var array1 = new int[] {1,2,3,45,56 };//automatycznie ustawiona wielkosc tablicy na:5
3. tables are indexed from 0
array1[2]=12345; //modyfikacja elementu
Console.WriteLine(array1[2]); //odczyt elementu
4. default values for table int = 0
5. default values for object table =NULL
6. how to display elements of array?
Console.WriteLine(array1);
for (int i=0;i<array1.Length;i++) { Console.WriteLine(array1[i]); }
7. how to add additional element at the end of table (remember table has const number of elements)
-create new table on the basis of the old one with length greater of 1 and at the end add new element
8. List
-table of vary length (you can add/delete/sort elements)
– better use list instead of tables!
9. how to create a list?
using System.Collections.Generic;
var list=new List(); //<> to jest typ generyczny
var list1=new List() {1,2,3,4,5,6};
10. adding elements
list.Add(5);
11. how to display element from the list?
a)first way
for (int i=0;i< list.Count;i++)
{
Console.WriteLine(list[i]);
}
b) second way [more profitable]
foreach(var item in list)
{
Console.WriteLine(item);
}
c)example
public class Student
{
public int Id {get;set;}
public string Name {get; set;}
public List grades {get; set;}
public Student()
{
Grades =new List();
}
}
public class Lecture
{
private readonly List _students;
public Lecture(List students)
{
_students=students;
}
public void AddLateStudents(List lateStudents)
{
_students.AddRange(lateStudents);
}
public void MakeExam()
{
var random=new Random();foreach (var student in _students) { student.Grades.Add(random.Next(101)); }
}
public void DisplayNumberOfStudents()
{
Console.WriteLine($"There are {_students.Count} students.");
}
public void DisplayAverageGrades()
{
foreach (var student in _students)
{
int gradeSum=0;
foreach (var grade in student.Grades)
{
gradeSum +=grade;
}
double average =(double)gradeSum/student.Grades.Count;Console.WriteLine($"Student {student.Name} has an average grade of {average.ToString("#.##")}% out of {student.Count}"); }
}
public void SortGradesForEachStudent(bool ascending=true) //parametr domyslny
{
foreach (var student in _students)
{if (ascending) { student.Grades.Sort(); //ascending } else { student.Grades.Reverse(); //descending } Console.WriteLine($"Student {student.Name} has following grades."); foreach(var grade in student.Grades) { Console.Write($"{grade} "); } }
}
}
class Program
{
static void Main(string[] args)
{
var student=new List()
{
new Student()
{
Id=1,
Name="John"
},
new Student()
{
Id=2,
Name="Ann"
},
new Student()
{
Id=3,
Name="Ann1"
}}; var lateStudents=new List() { new Student() { Id=4, Name="John2" }, new Student() { Id=5, Name="Ann2" } }; var lecture=new Lecture(student); lecture.DisplayNumberOfStudents(); lecture.MakeExam(); lecture.AddLateStudents(lateStudents); lecture.DisplayNumberOfStudents(); lecture.MakeExam(); lecture.DisplayAverageofGrades(); Console.WriteLine("-------------------------"); lecture.SortGradesForEachStudent(ascending:true);
}
}
12. Dictionary,stack, queue
a) Dictionary – collection with elements as pair: key->value (ie. word and its translation); Keys must be unique!!! (can be created using hash function)
class Student
{
public Dictionary PhoneNumbers {get; set;} //pierwszy typ->klucz; drugi typ->wartosc
public Student()
{
Grades=new List();
PhoneNumbers=new dictionary();
}
public void AddPhoneNumber(string name,int number)
{
PhoneNumbers.Add(name,number);
}
public void DisplayPhoneNumber(string name)
{
var number=PhoneNumbers[name];
}
}
b) how to ensure that keys are unique?
public void AddPhoneNumberSafely(string name,int number)
{
var success= PhoneNumbers.TryAdd(name,number); //ta metoda probuje dodac nr o tym kluczu i zwraca wart. czy sie udalo czy nie
if (!success)
{
Console.WriteLine("Nie udalo sie dodac tego nr-klucz istnieje");
}
}
c) what will happen when we try to use nonexisting key?
student.DisplayPhoneNumber("Fax");//bedzie exception!
//jak to obejsc?
public void DisplayPhoneNumberSafely(string name)
{
//out - to jest przekazywanie przez referencje!
var success=PhoneNumbers.TryGetValue(name,out int number);
if (!success)
{
Console.WriteLine("ojej - nie udalo sie pobrac nr-bo nie istnieje!");
}
}
d) how to display the whole dictionary?
foreach (var number in PhoneNumbers)
{
Console.WriteLine($"Name: {number.key}= {number.value}");
}
13. Stack
-data structure of type LIFO (as stcak of plates on the table)
-we have access only to element, which is on the top of the stack
-we can use it as implementation of 'Undo’ in Text editor
var stack=new Stack();
14. Queue
-data structure of type FIFO(like in the shop)
-we have access to the first element
var queue=new Queue();
15. Naming convention
– parameters in methods – caps
– class and methods – camelcase
-private parameters – _nazwa
16.How to sort list of objects?
public void SortStudentByAverage()
{
_students.Sort(new StudentComparer());
}
17. how to create own comparator?
using System.Diagnostics.CodeAnalysis;
public class StudentComparer:IComparer
{
private double Calculate(Student student)
{
int sum=0;
foreach(var grade in student.Grades)
{
sum +=grade;
}
double average=(double)sum/student.Grades.Count();
return Math.Round(average,2);
}
public int Compare([AllowNull] Student x,[AllowNull] Student y)
{
var averageX = CalculateAverage(x);
var averageY = CalculateAverage(y);
if (averageX-averageY >0)
{
return 1;
}
if (averageX-averageY ==0)
{
return 0;
}
if (averageX-averageY <0)
{
return -1;
}
}
}