
If (File.Exists(filename))
{
try
{
file = File.OpenRead(filename);
BinaryFormatter formatter = new BinaryFormatter();
Student student = (Student)formatter.Deserialize(file);
obj.name = student.name;
obj.surname = student.surname;
obj.dateOfBirth = student.dateOfBirth;
obj.FormOfEducation = student.formOfEducation;
obj.groupNumber = student.groupNumber;
obj.exams = student.exams;
//obj.exams.AddRange(student.exams);
obj.tests = student.tests;
//file.Close();
return true;
}
catch
{
Console.WriteLine("Проблемы при загрузке из файла (static): " + filename);
//file.Close();
return false;
}
finally
{
file.Close();
}
}
else
{
Console.WriteLine("Файла с таким названием не существет (static): " + filename);
return false;
}
}
// перебор всех зачётов и экзаменов
public IEnumerable TestExam()
{
foreach (Test test in this.tests)
{
yield return test;
}
foreach (Exam exam in this.exams)
{
yield return exam;
}
}
public IEnumerable GetExams(int grade)
{
foreach (Exam exam in exams)
{
if (exam.grade > grade)
{
yield return exam;
}
}
}
public IEnumerator GetEnumerator()
{
return new StudentEnumerator(exams, tests);
}
public IEnumerable ExamTestDone()
{
foreach (Exam exam in this.GetExams(2))
{
yield return exam;
}
foreach (Test test in this.tests)
{
if (test.status == true)
{
yield return test;
}
}
}
public IEnumerable TestWithExamDone()
{
foreach (Test test in this.tests)
{
if (test.status == true)
{
foreach (Exam exam in this.GetExams(2))
{
if (test.subject == exam.subject)
{
yield return test;
}
}
}
}
}
public void sortingSubject()
{
exams.Sort();
}
public void sortingGrade()
{
IComparer<Exam> grade = new Exam();
exams.Sort(grade);
}
public void sortingDate()
{
IComparer<Exam> date = new ExamDateCompare();
exams.Sort(date);
}
}
class StudentEnumerator : IEnumerator
{
List<Exam> exams;
List<Test> tests;
int index;
public StudentEnumerator(List<Exam> exams, List<Test> tests)
{
this.exams = exams;
this.tests = tests;
index = -1;
}
public object Current
{
get
{
return exams[index];
}
}
public bool MoveNext()
{
for (int i = index + 1; i < exams.Count; i++)
{
foreach (var test in tests)
{
if (((Test)test).subject == ((Exam)exams[i]).subject)
{
index = i;
return true;
}
}
}
return false;
}
public void Reset()
{
index = -1;
}
}
// коллекция студентов
class StudentCollection<TKey>
{
private Dictionary<TKey, Student> studentDict;
private KeySelector<TKey> tKey; // выбор ключа
public string CollectionName { get; set; }
public StudentCollection(KeySelector<TKey> tKey)
{
studentDict = new Dictionary<TKey, Student>();
this.tKey = tKey;
}
// обработчик события PropertyChanged
public void EventHendler(object subject, PropertyChangedEventArgs e)
{
//PropertyChangedEventArgs propertyName = e;
var student = (Student)subject;
TKey key = tKey(student);
//StudentPropertyChanged(Action.Property, e.PropertyName.ToString(), key);
StudentsChanged?.Invoke(this, new StudentsChangedEventArgs<TKey>(CollectionName, Action.Property, e.PropertyName, key));
}
public event StudentsChangedHandler<TKey> StudentsChanged;
private void StudentPropertyChanged(Action eventInformation, string propertyName, TKey elementKey)
{
StudentsChanged?.Invoke(this, new StudentsChangedEventArgs<TKey>(CollectionName, eventInformation, propertyName, elementKey));
}
public void AddDefaults()
{
Student student = new Student();
TKey key = tKey(student);
studentDict.Add(key, student);
//StudentPropertyChanged(Action.Add, "StudentCollection", key);
StudentsChanged?.Invoke(this, new StudentsChangedEventArgs<TKey>(CollectionName, Action.Add, "StudentCollection", key));
student.PropertyChanged += EventHendler; // подписка на событие
}
//добавление одного или несколько студентов в словаь
public void AddStudents(params Student[] students)
{
foreach (Student student in students)
{
TKey key = tKey(student);
studentDict.Add(key, student);
//StudentPropertyChanged(Action.Add, "StudentCollection", key);
StudentsChanged?.Invoke(this, new StudentsChangedEventArgs<TKey>(CollectionName, Action.Add, "StudentCollection", key));
student.PropertyChanged += EventHendler; // подписка на событие
}
}
public bool Remove(Student st)
{
TKey key = tKey(st);
if (studentDict.ContainsKey(key) == true)
{
studentDict.Remove(key);
//StudentPropertyChanged(Action.Remove, "StudentCollection", key);
StudentsChanged?.Invoke(this, new StudentsChangedEventArgs<TKey>(CollectionName, Action.Remove, "StudentCollection", key));
st.PropertyChanged -= EventHendler;
return true;
}
return false;
}
public override string ToString()
{
foreach (var student in studentDict)
{
Console.WriteLine("Key: " + student.Key.ToString());
Console.WriteLine(student.Value.ToString());
}
return " ";
}
public string ToShortString()
{
foreach (var student in studentDict)
{
Console.WriteLine("Key: " + student.Key.ToString());
Console.WriteLine(student.Value.ToShortString());
}
return " ";
}
// максимальный средний балл среди всех студентов
public double MaxAverage
{
get
{
if (studentDict.Count > 0)
{
return studentDict.Values.Max(max => max.AverageGrade);
}
return 0;
}
}
// возвращает элементы, содержащие переданную форму образования
public IEnumerable<KeyValuePair<TKey, Student>> EducationForm(Education value)
{
return studentDict.Where(form => form.Value.FormOfEducation == value);
}
// группировка элементов по форме обучения
public IEnumerable<IGrouping<Education, KeyValuePair<TKey, Student>>> GroupEducation
{
get
{
return studentDict.GroupBy(form => form.Value.FormOfEducation);
}
}
}
class StudentsChangedEventArgs<TKey> : EventArgs
{
public string CollectionName { get; set; }
public Action EventInformation { get; set; }
public string PropertyName { get; set; }
public TKey ElementKey { get; set; }
public StudentsChangedEventArgs(string CollectionName, Action EventInformation, string PropertyName, TKey ElementKey)
{
this.CollectionName = CollectionName;
this.EventInformation = EventInformation;
this.PropertyName = PropertyName;
this.ElementKey = ElementKey;
}
public override string ToString()
{
return $"Название коллекции: {CollectionName}\nСобытие вызвано: {EventInformation}\nСвойство, которое является источником изменений: {PropertyName}\nКлюч элемента: {ElementKey}\n";
}
}
class JournalEntry
{
public string CollectionName { get; set; }
public Action EventInformation { get; set; }
public string PropertyName { get; set; }
public string Key { get; set; }
public JournalEntry(string CollectionName, Action EventInformation, string PropertyName, string Key)
{
this.CollectionName = CollectionName;
this.EventInformation = EventInformation;
this.PropertyName = PropertyName;
this.Key = Key;
}
public override string ToString()
{
return $"Название коллекции: {CollectionName}\nСобытие вызвано: {EventInformation}\nСвойство, которое является источником изменений: {PropertyName}\nКлюч элемента: {Key}\n";
}
}
class Journal
{
private List<JournalEntry> journalList = new List<JournalEntry>();
//обработчик события StudentsChanged
public void AddListEntry(object subject, StudentsChangedEventArgs<string> e)
{
//StudentsChangedEventArgs<string> eventArgs = e;
JournalEntry newListEntry = new JournalEntry(e.CollectionName, e.EventInformation, e.PropertyName, e.ElementKey.ToString());
journalList.Add(newListEntry);
}
/*
public void NewListEntry2(object subject, EventArgs e)
{
var me = (PropertyChangedEventArgs)e;
JournalEntry newListEntry = new JournalEntry("", Action.Property, me.PropertyName.ToString(), "");
journalList.Add(newListEntry);
}
*/
public override string ToString()
{
foreach (JournalEntry journal in journalList)
{
Console.WriteLine(journal.ToString());
}
return "";
}
}
[Serializable]
class Test
{
public string subject { get; set; }
public bool status { get; set; }
public Test(string subject, bool status)
{
this.subject = subject;
this.status = status;
}
public Test()
{
subject = "Subject";
status = true;
}
public override string ToString()
{
return $"Предмет: {subject}, Зачёт: {status}";
}
}
class TestCollections<TKey, TValue>
{
private List<TKey> tKeyList = new List<TKey>();
private List<string> stringList = new List<string>();
private Dictionary<TKey, TValue> tKeyDict = new Dictionary<TKey, TValue>();
private Dictionary<string, TValue> stringDict = new Dictionary<string, TValue>();
private GenerateElement<TKey, TValue> generateElement;
/*
public TestCollections()
{
tKeyList = new List<TKey>();
stringList = new List<string>();
tKeyDict = new Dictionary<TKey, TValue>();
stringDict = new Dictionary<string, TValue>();
}
*/
public TestCollections(int number, GenerateElement<TKey, TValue> method)
{
generateElement = method;
for (int i = 0; i < number; i++)
{
var element = generateElement(i); //Для каждого индекса вызывается делегат generateElement, который генерирует ключ и значение элемента
tKeyList.Add(element.Key);
stringList.Add(element.Key.ToString());
tKeyDict.Add(element.Key, element.Value);
stringDict.Add(element.Key.ToString(), element.Value);
}
}
public void searchTimeTKeyList()
{
var first = tKeyList[0];
var centeral = tKeyList[tKeyList.Count / 2];
var last = tKeyList[tKeyList.Count - 1];
var notBelonging = generateElement(tKeyList.Count * 2).Key;
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
Console.WriteLine("---Время для List<TKey >---");
watch.Start();
tKeyList.Contains(first);
watch.Stop();
Console.WriteLine("Время для первого элемента: " + watch.Elapsed);
watch.Restart();
tKeyList.Contains(centeral);
watch.Stop();
Console.WriteLine("Время для центрального элемента: " + watch.Elapsed);
watch.Restart();
tKeyList.Contains(last);
watch.Stop();
Console.WriteLine("Время для последнего элемента: " + watch.Elapsed);
watch.Restart();
tKeyList.Contains(notBelonging);
watch.Stop();
Console.WriteLine("Врамя для элемента, не входящего в коллекцию: " + watch.Elapsed + "\n");
}
public void searchTimeStringList()
{
var first = stringList[0];
var centeral = stringList[stringList.Count / 2];
var last = stringList[stringList.Count - 1];
var notBelonging = generateElement(stringList.Count * 2).Key.ToString();
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
Console.WriteLine("---Время для List<string >---");
watch.Start();
stringList.Contains(first);
watch.Stop();
Console.WriteLine("Время для первого элемента: " + watch.Elapsed);
watch.Restart();
stringList.Contains(centeral);
watch.Stop();
Console.WriteLine("Время для центрального элемента: " + watch.Elapsed);
watch.Restart();
stringList.Contains(last);
watch.Stop();
Console.WriteLine("Время для последнего элемента: " + watch.Elapsed);
watch.Restart();
stringList.Contains(notBelonging);
watch.Stop();
Console.WriteLine("Врамя для элемента, не входящего в коллекцию: " + watch.Elapsed + "\n");
}
public void searchTimeTKeyDictKey()
{
var first = tKeyDict.ElementAt(0).Key;
var centeral = tKeyDict.ElementAt(tKeyDict.Count / 2).Key;
var last = tKeyDict.ElementAt(tKeyDict.Count - 1).Key;
var notBelonging = generateElement(tKeyDict.Count * 2).Key;
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
Console.WriteLine("---Время по ключу для Dictionary< TKey, TValue >---");
watch.Start();
tKeyDict.ContainsKey(first);
watch.Stop();
Console.WriteLine("Время для первого элемента: " + watch.Elapsed);
watch.Restart();
tKeyDict.ContainsKey(centeral);
watch.Stop();
Console.WriteLine("Время для центрального элемента: " + watch.Elapsed);
watch.Restart();
tKeyDict.ContainsKey(last);
watch.Stop();
Console.WriteLine("Время для последнего элемента: " + watch.Elapsed);
watch.Restart();
tKeyDict.ContainsKey(notBelonging);
watch.Stop();
Console.WriteLine("Врамя для элемента, не входящего в коллекцию: " + watch.Elapsed + "\n");
}
public void searchTimeStringDictKey()
{
var first = stringDict.ElementAt(0).Key;
var centeral = stringDict.ElementAt(stringDict.Count / 2).Key;
var last = stringDict.ElementAt(stringDict.Count - 1).Key;
var notBelonging = generateElement(stringDict.Count * 2).Key.ToString();
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
Console.WriteLine("---Время по ключу для Dictionary< string, TValue >---");
watch.Start();
stringDict.ContainsKey(first);
watch.Stop();
Console.WriteLine("Время для первого элемента: " + watch.Elapsed);
watch.Restart();
stringDict.ContainsKey(centeral);
watch.Stop();
Console.WriteLine("Время для центрального элемента: " + watch.Elapsed);
watch.Restart();
stringDict.ContainsKey(last);
watch.Stop();
Console.WriteLine("Время для последнего элемента: " + watch.Elapsed);
watch.Restart();
stringDict.ContainsKey(notBelonging);
watch.Stop();
Console.WriteLine("Врамя для элемента, не входящего в коллекцию: " + watch.Elapsed + "\n");
}
public void searchTimeTKeyDictValue()
{
var first = tKeyDict.ElementAt(0).Value;
var centeral = tKeyDict.ElementAt(tKeyDict.Count / 2).Value;
var last = tKeyDict.ElementAt(tKeyDict.Count - 1).Value;
var notBelonging = generateElement(tKeyDict.Count * 2).Value;
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
Console.WriteLine("---Время по значению для Dictionary< TKey, TValue >---");
watch.Start();
tKeyDict.ContainsValue(first);
watch.Stop();
Console.WriteLine("Время для первого элемента: " + watch.Elapsed);
watch.Restart();
tKeyDict.ContainsValue(centeral);
watch.Stop();
Console.WriteLine("Время для центрального элемента: " + watch.Elapsed);
watch.Restart();
tKeyDict.ContainsValue(last);
watch.Stop();
Console.WriteLine("Время для последнего элемента: " + watch.Elapsed);
watch.Restart();
tKeyDict.ContainsValue(notBelonging);
watch.Stop();
Console.WriteLine("Врамя для элемента, не входящего в коллекцию: " + watch.Elapsed + "\n");
}
public void searchTimeStringDictValue()
{
var first = stringDict.ElementAt(0).Value;
var centeral = stringDict.ElementAt(stringDict.Count / 2).Value;
var last = stringDict.ElementAt(stringDict.Count - 1).Value;
var notBelonging = generateElement(stringDict.Count * 2).Value;
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
Console.WriteLine("---Время по значению для Dictionary< string, TValue >---");
watch.Start();
stringDict.ContainsValue(first);
watch.Stop();
Console.WriteLine("Время для первого элемента: " + watch.Elapsed);
watch.Restart();
stringDict.ContainsValue(centeral);
watch.Stop();
Console.WriteLine("Время для центрального элемента: " + watch.Elapsed);
watch.Restart();
stringDict.ContainsValue(last);
watch.Stop();
Console.WriteLine("Время для последнего элемента: " + watch.Elapsed);
watch.Restart();
stringDict.ContainsValue(notBelonging);
watch.Stop();
Console.WriteLine("Врамя для элемента, не входящего в коллекцию: " + watch.Elapsed + "\n");
}
}
namespace LAB_2_PROVERKA
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("---№1---");
Student studentOne = new Student(new Person("Alex", "Dark", new DateTime(2004, 4, 12)), Education.Bachelor, 200);
studentOne.AddExams(new Exam("Java", 3, new DateTime(2022, 6, 16)), new Exam("C#", 4, new DateTime(2022, 7, 3)));
//studentOne.AddTests(new Test("ЭВМ", true), new Test("Английский язык", false), new Test("Python", true));
try
{
Student studentOneCopy = studentOne.DeepCopySerialization();
Console.WriteLine("Оригинал: ");
Console.WriteLine(studentOne.ToString());
Console.WriteLine("\nКопия: ");
Console.WriteLine(studentOneCopy.ToString());
}
catch
{
Console.WriteLine("Проблемы при сериализации! (1)");
}
Console.WriteLine("\n---№2---");
Console.Write("Введите имя файла без формата: ");
string userFileName = Console.ReadLine() + ".bin";
try
{
//if (File.Exists(userFileName))
//{