From 50755f3d532db604d092fb12b1e9f9edc3f38a85 Mon Sep 17 00:00:00 2001 From: gettterot Date: Mon, 10 Jun 2024 05:33:55 +0400 Subject: [PATCH 1/5] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=20DrawningLinerEqutables?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ICollectionGenericObjects.cs | 12 +++- .../Drawnings/DrawningLinerEqutables.cs | 71 +++++++++++++++++++ 2 files changed, 81 insertions(+), 2 deletions(-) create mode 100644 ProjectLiner/ProjectLiner/Drawnings/DrawningLinerEqutables.cs diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ICollectionGenericObjects.cs index faf079d..e8f7baa 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -21,16 +21,18 @@ /// Добавление объекта в коллекцию /// /// Добавляемый объект + /// /// Сравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция + /// /// Сравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -56,5 +58,11 @@ /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// + void CollectionSort(IComparer comparer); } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/Drawnings/DrawningLinerEqutables.cs b/ProjectLiner/ProjectLiner/Drawnings/DrawningLinerEqutables.cs new file mode 100644 index 0000000..f1cbb56 --- /dev/null +++ b/ProjectLiner/ProjectLiner/Drawnings/DrawningLinerEqutables.cs @@ -0,0 +1,71 @@ +using ProjectLiner.Drawnings; +using ProjectLiner.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawningLinerEqutables : IEqualityComparer +{ + public bool Equals(DrawningCommonLiner x, DrawningCommonLiner? y) + { + if (x == null || x.EntityCommonLiner == null) + { + return false; + } + if (y == null || y.EntityCommonLiner == null) + { + return false; + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityCommonLiner.Speed != y.EntityCommonLiner.Speed) + { + return false; + } + if (x.EntityCommonLiner.Weight != y.EntityCommonLiner.Weight) + { + return false; + } + if (x.EntityCommonLiner.BodyColor != y.EntityCommonLiner.BodyColor) + { + return false; + } + if (x is DrawningLiner && y is DrawningLiner) + { + if (((EntityLiner)x.EntityCommonLiner).AdditionalColor != + ((EntityLiner)y.EntityCommonLiner).AdditionalColor) + { + return false; + } + if (((EntityLiner)x.EntityCommonLiner).Boats != + ((EntityLiner)y.EntityCommonLiner).Boats) + { + return false; + } + if (((EntityLiner)x.EntityCommonLiner).Anchor != + ((EntityLiner)y.EntityCommonLiner).Anchor) + { + return false; + } + if (((EntityLiner)x.EntityCommonLiner).Pipe != + ((EntityLiner)y.EntityCommonLiner).Pipe) + { + return false; + } + } + return true; + } + + public int GetHashCode([DisallowNull] DrawningCommonLiner obj) + { + return obj.GetHashCode(); + } +} \ No newline at end of file -- 2.25.1 From 859a9ffff60e41f42cc7a20cae0a35158319f8fb Mon Sep 17 00:00:00 2001 From: gettterot Date: Mon, 10 Jun 2024 05:44:42 +0400 Subject: [PATCH 2/5] =?UTF-8?q?=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B8=D0=BB?= =?UTF-8?q?=D0=B8=20Insert=20d=20massive=20=D0=B8=20list,=20=D1=82=D0=B0?= =?UTF-8?q?=D0=BA=D0=B6=D0=B5=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB?= =?UTF-8?q?=D0=B8=20=D0=BD=D0=BE=D0=B2=D1=8B=D0=B9=20=D0=BA=D0=BB=D0=B0?= =?UTF-8?q?=D1=81=D1=81=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ListGenericObjects.cs | 27 ++++++++---- .../MassiveGenericObjects.cs | 41 +++++++++++++------ .../ObjectAlreadyExistsException.cs | 22 ++++++++++ 3 files changed, 70 insertions(+), 20 deletions(-) create mode 100644 ProjectLiner/ProjectLiner/Exceptions/ObjectAlreadyExistsException.cs diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs index d37225b..a9066aa 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs @@ -58,20 +58,31 @@ namespace ProjectLiner.CollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - if (Count >= _maxCount) - throw new CollectionOverflowException(Count); + if (Count == _maxCount) throw new CollectionOverflowException(); + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectAlreadyExistsException(obj); + } + } _collection.Add(obj); return Count; } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - if (Count == _maxCount) - throw new CollectionOverflowException(Count); - if (position < 0 || position > Count) - throw new PositionOutOfCollectionException(position); ; + if (Count == _maxCount) throw new CollectionOverflowException(); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectAlreadyExistsException(obj); + } + } _collection.Insert(position, obj); return position; } diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs index 99f8a17..e8b40f5 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs @@ -61,8 +61,18 @@ namespace ProjectLiner.CollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { + if (comparer != null) + { + foreach (T? i in _collection) + { + if (comparer.Equals(i, obj)) + { + throw new ObjectAlreadyExistsException(i); + } + } + } for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -71,20 +81,29 @@ namespace ProjectLiner.CollectionGenericObjects return i; } } - throw new CollectionOverflowException(Count); + throw new CollectionOverflowException(); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - if (position >= Count || position < 0) - throw new PositionOutOfCollectionException(position); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); + + if (comparer != null) + { + foreach (T? i in _collection) + { + if (comparer.Equals(i, obj)) + { + throw new ObjectAlreadyExistsException(i); + } + } + } if (_collection[position] == null) { _collection[position] = obj; return position; } - int temp = position + 1; while (temp < Count) { @@ -93,21 +112,19 @@ namespace ProjectLiner.CollectionGenericObjects _collection[temp] = obj; return temp; } - temp++; + ++temp; } - temp = position - 1; - while (temp > 0) + while (temp >= 0) { if (_collection[temp] == null) { _collection[temp] = obj; return temp; } - temp--; + --temp; } - - throw new CollectionOverflowException(Count); + throw new CollectionOverflowException(); } public T? Remove(int position) diff --git a/ProjectLiner/ProjectLiner/Exceptions/ObjectAlreadyExistsException.cs b/ProjectLiner/ProjectLiner/Exceptions/ObjectAlreadyExistsException.cs new file mode 100644 index 0000000..8cbb498 --- /dev/null +++ b/ProjectLiner/ProjectLiner/Exceptions/ObjectAlreadyExistsException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectLiner.Exceptions; + +/// +/// Класс, описывающий ошибку, что в коллекции уже есть такой элемент +/// +[Serializable] +public class ObjectAlreadyExistsException : ApplicationException +{ + public ObjectAlreadyExistsException(object i) : base("В коллекции уже есть такой элемент " + i) { } + public ObjectAlreadyExistsException() : base() { } + public ObjectAlreadyExistsException(string message) : base(message) { } + public ObjectAlreadyExistsException(string message, Exception exception) : base(message, exception) + { } + protected ObjectAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} -- 2.25.1 From 5c7b6d8bf223a03124f371e0a33becbc78c41679 Mon Sep 17 00:00:00 2001 From: gettterot Date: Mon, 10 Jun 2024 05:54:10 +0400 Subject: [PATCH 3/5] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB?= =?UTF-8?q?=D0=B8=20DrawningLinerCompareByType?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 4 +- .../Drawnings/DrawningLinerCompareByType.cs | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 ProjectLiner/ProjectLiner/Drawnings/DrawningLinerCompareByType.cs diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs index c85dc44..3ccc120 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs @@ -60,9 +60,9 @@ namespace ProjectLiner.CollectionGenericObjects /// Компания /// Добавляемый объект /// - public static int operator +(AbstractCompany company, DrawningCommonLiner airplane) + public static int operator +(AbstractCompany company, DrawningCommonLiner liner) { - return company._collection.Insert(airplane); + return company._collection.Insert(liner, new DrawningLinerEqutables() ); } /// diff --git a/ProjectLiner/ProjectLiner/Drawnings/DrawningLinerCompareByType.cs b/ProjectLiner/ProjectLiner/Drawnings/DrawningLinerCompareByType.cs new file mode 100644 index 0000000..55584e5 --- /dev/null +++ b/ProjectLiner/ProjectLiner/Drawnings/DrawningLinerCompareByType.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectLiner.Drawnings; +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningLinerCompareByType : IComparer +{ + + public int Compare(DrawningCommonLiner? x, DrawningCommonLiner? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityCommonLiner == null) + { + return 1; + } + + if (y == null || y.EntityCommonLiner == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityCommonLiner.Speed.CompareTo(y.EntityCommonLiner.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityCommonLiner.Weight.CompareTo(y.EntityCommonLiner.Weight); + } +} -- 2.25.1 From 996797c794f2e879edee412c74f7d1be08e6f12b Mon Sep 17 00:00:00 2001 From: gettterot Date: Mon, 10 Jun 2024 06:37:56 +0400 Subject: [PATCH 4/5] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB?= =?UTF-8?q?=D0=B8=20=D1=81=D0=BE=D1=80=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=BA?= =?UTF-8?q?=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 6 +++ .../ListGenericObjects.cs | 5 ++ .../MassiveGenericObjects.cs | 4 ++ .../Drawnings/DrawningLinerCompareByColor.cs | 38 +++++++++++++++ .../FormLinerCollection.Designer.cs | 48 +++++++++++++++---- .../ProjectLiner/FormLinerCollection.cs | 27 +++++++++++ 6 files changed, 119 insertions(+), 9 deletions(-) create mode 100644 ProjectLiner/ProjectLiner/Drawnings/DrawningLinerCompareByColor.cs diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs index 3ccc120..9fb1c6b 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs @@ -130,5 +130,11 @@ namespace ProjectLiner.CollectionGenericObjects /// Расстановка объектов /// protected abstract void SetObjectsPosition(); + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs index a9066aa..d185e41 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs @@ -104,5 +104,10 @@ namespace ProjectLiner.CollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } } diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs index e8b40f5..809c602 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs @@ -147,5 +147,9 @@ namespace ProjectLiner.CollectionGenericObjects yield return _collection[i]; } } + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/Drawnings/DrawningLinerCompareByColor.cs b/ProjectLiner/ProjectLiner/Drawnings/DrawningLinerCompareByColor.cs new file mode 100644 index 0000000..2c83c06 --- /dev/null +++ b/ProjectLiner/ProjectLiner/Drawnings/DrawningLinerCompareByColor.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectLiner.Drawnings; + + +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningLinerCompareByColor : IComparer +{ + public int Compare(DrawningCommonLiner? x, DrawningCommonLiner? y) + { + if (x == null || x.EntityCommonLiner == null) + { + return 1; + } + + if (y == null || y.EntityCommonLiner == null) + { + return -1; + } + var bodycolorCompare = x.EntityCommonLiner.BodyColor.Name.CompareTo(y.EntityCommonLiner.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + var speedCompare = x.EntityCommonLiner.Speed.CompareTo(y.EntityCommonLiner.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityCommonLiner.Weight.CompareTo(y.EntityCommonLiner.Weight); + } +} diff --git a/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs b/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs index eb6b44c..58de58f 100644 --- a/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs +++ b/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); openFileDialog = new OpenFileDialog(); saveFileDialog = new SaveFileDialog(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); groupBoxTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); @@ -67,7 +69,7 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(1052, 49); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(272, 1014); + groupBoxTools.Size = new Size(272, 1140); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -190,7 +192,7 @@ // pictureBox.Dock = DockStyle.Bottom; pictureBox.Enabled = false; - pictureBox.Location = new Point(0, 51); + pictureBox.Location = new Point(0, 177); pictureBox.Name = "pictureBox"; pictureBox.Size = new Size(1052, 1012); pictureBox.TabIndex = 1; @@ -199,6 +201,8 @@ // panelCompanyTools // panelCompanyTools.BackColor = SystemColors.Window; + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddLiner); panelCompanyTools.Controls.Add(maskedTextBox1); panelCompanyTools.Controls.Add(button5); @@ -207,14 +211,14 @@ panelCompanyTools.Location = new Point(1052, 592); panelCompanyTools.Margin = new Padding(5); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(272, 470); + panelCompanyTools.Size = new Size(272, 589); panelCompanyTools.TabIndex = 9; // // buttonAddLiner // buttonAddLiner.Location = new Point(6, 54); buttonAddLiner.Name = "buttonAddLiner"; - buttonAddLiner.Size = new Size(214, 75); + buttonAddLiner.Size = new Size(242, 75); buttonAddLiner.TabIndex = 7; buttonAddLiner.Text = "Добавить"; buttonAddLiner.UseVisualStyleBackColor = true; @@ -225,7 +229,7 @@ maskedTextBox1.Location = new Point(3, 167); maskedTextBox1.Mask = "00"; maskedTextBox1.Name = "maskedTextBox1"; - maskedTextBox1.Size = new Size(217, 47); + maskedTextBox1.Size = new Size(245, 47); maskedTextBox1.TabIndex = 3; maskedTextBox1.ValidatingType = typeof(int); // @@ -234,7 +238,7 @@ button5.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; button5.Location = new Point(3, 384); button5.Name = "button5"; - button5.Size = new Size(216, 75); + button5.Size = new Size(245, 75); button5.TabIndex = 6; button5.Text = "Обновить"; button5.UseVisualStyleBackColor = true; @@ -245,7 +249,7 @@ button3.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; button3.Location = new Point(3, 220); button3.Name = "button3"; - button3.Size = new Size(216, 75); + button3.Size = new Size(245, 75); button3.TabIndex = 4; button3.Text = "Удаление Лайнера"; button3.UseVisualStyleBackColor = true; @@ -256,7 +260,7 @@ button4.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; button4.Location = new Point(3, 302); button4.Name = "button4"; - button4.Size = new Size(216, 75); + button4.Size = new Size(245, 75); button4.TabIndex = 5; button4.Text = "Передать на тесты"; button4.UseVisualStyleBackColor = true; @@ -304,11 +308,35 @@ // saveFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Font = new Font("Segoe UI", 9.818182F, FontStyle.Regular, GraphicsUnit.Point); + buttonSortByColor.Location = new Point(3, 526); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(245, 44); + buttonSortByColor.TabIndex = 9; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Font = new Font("Segoe UI", 9.818182F, FontStyle.Regular, GraphicsUnit.Point); + buttonSortByType.Location = new Point(4, 476); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(244, 44); + buttonSortByType.TabIndex = 8; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // // FormLinerCollection // AutoScaleDimensions = new SizeF(17F, 41F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1324, 1063); + ClientSize = new Size(1324, 1189); Controls.Add(panelCompanyTools); Controls.Add(pictureBox); Controls.Add(groupBoxTools); @@ -358,5 +386,7 @@ private ToolStripMenuItem loadToolStripMenuItem; private OpenFileDialog openFileDialog; private SaveFileDialog saveFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/FormLinerCollection.cs b/ProjectLiner/ProjectLiner/FormLinerCollection.cs index a96fe40..ed4a241 100644 --- a/ProjectLiner/ProjectLiner/FormLinerCollection.cs +++ b/ProjectLiner/ProjectLiner/FormLinerCollection.cs @@ -325,5 +325,32 @@ namespace ProjectLiner } } } + + /// + /// Сортировка по типу + /// + /// + /// + private void buttonSortByType_Click(object sender, EventArgs e) => CompareTrucks(new DrawningLinerCompareByType()); + + /// + /// Сортировка по цвету + /// + /// + /// + private void buttonSortByColor_Click(object sender, EventArgs e) => CompareTrucks(new DrawningLinerCompareByColor()); + + /// + /// Сортировка по сравнителю + /// + private void CompareTrucks(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } } \ No newline at end of file -- 2.25.1 From 34abba54cc0b4cb75dbc0e83d20650bca1f096a2 Mon Sep 17 00:00:00 2001 From: gettterot Date: Mon, 10 Jun 2024 07:35:07 +0400 Subject: [PATCH 5/5] =?UTF-8?q?8=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CollectionInfo.cs | 74 +++ .../MassiveGenericObjects.cs | 4 +- .../StorageCollection.cs | 427 +++++++++--------- .../ProjectLiner/FormLinerCollection.cs | 7 +- 4 files changed, 294 insertions(+), 218 deletions(-) create mode 100644 ProjectLiner/ProjectLiner/CollectionGenericObjects/CollectionInfo.cs diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/CollectionInfo.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..4c792b2 --- /dev/null +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,74 @@ +using ProjectLiner.CollectionGenericObjects; + +namespace ProjectLiner.CollectionGenericObjects; + +/// +/// Класс, хранящиий информацию по коллекции +/// +public class CollectionInfo : IEquatable +{ + /// + /// Название + /// + public string Name { get; private set; } + /// + /// Тип + /// + public CollectionType CollectionType { get; private set; } + /// + /// Описание + /// + public string Description { get; private set; } + + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separator = "-"; + + /// + /// Конструктор + /// + /// Название + /// Тип + /// Описание + public CollectionInfo(string name, CollectionType collectionType, string description) + { + Name = name; + CollectionType = collectionType; + Description = description; + } + + /// + /// Создание объекта из строки + /// + /// Строка + /// Объект или null + public static CollectionInfo? GetCollectionInfo(string data) + { + string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries); + if (strs.Length < 1 || strs.Length > 3) + { + return null; + } + return new CollectionInfo(strs[0], + (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? strs[2] : string.Empty); + } + + public override string ToString() + { + return Name + _separator + CollectionType + _separator + Description; + } + + public bool Equals(CollectionInfo? other) + { + return Name == other?.Name; + } + public override bool Equals(object? obj) + { + return Equals(obj as CollectionInfo); + } + public override int GetHashCode() + { + return Name.GetHashCode(); + } +} \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs index 809c602..a4a8b16 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs @@ -69,7 +69,7 @@ namespace ProjectLiner.CollectionGenericObjects { if (comparer.Equals(i, obj)) { - throw new ObjectAlreadyExistsException(i); + throw new ObjectAlreadyExistsException(1); } } } @@ -94,7 +94,7 @@ namespace ProjectLiner.CollectionGenericObjects { if (comparer.Equals(i, obj)) { - throw new ObjectAlreadyExistsException(i); + throw new ObjectAlreadyExistsException(position); } } } diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs index c434e79..b0eab91 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs @@ -1,226 +1,223 @@ -using System.Data; -using System.IO; -using System.Text; + +using ProjectLiner.CollectionGenericObjects; using ProjectLiner.Drawnings; using ProjectLiner.Exceptions; -using ProjectLiner.CollectionGenericObjects; -using ProjectLiner.Exceptions; +using System.Data; +using System.Text; +using System.Xml.Linq; -namespace ProjectLiner.CollectionGenericObjects +namespace ProjectLiner.CollectionGenericObjects; + +/// +/// Класс-хранилище коллекций +/// +/// +public class StorageCollection + where T : DrawningCommonLiner { /// - /// Класс-хранилище коллекций + /// Словарь (хранилище) с коллекциями /// - /// - public class StorageCollection - where T : DrawningCommonLiner + readonly Dictionary> _storages; + + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Возвращение списка названий коллекций + /// + public List Keys => _storages.Keys.ToList(); + + /// + /// Конструктор + /// + public StorageCollection() { - /// - /// Словарь (хранилище) с коллекциями - /// - readonly Dictionary> _storages; - - /// - /// Возвращение списка названий коллекций - /// - public List Keys => _storages.Keys.ToList(); - - /// - /// Ключевое слово, с которого должен начинаться файл - /// - private readonly string _collectionKey = "CollectionsStorage"; - - /// - /// Разделитель для записи ключа и значения элемента словаря - /// - private readonly string _separatorForKeyValue = "|"; - - /// - /// Разделитель для записей коллекции данных в файл - /// - private readonly string _separatorItems = ";"; - - /// - /// Конструктор - /// - public StorageCollection() + _storages = new Dictionary>(); + } + /// + /// Добавление коллекции в хранилище + /// + /// Название коллекции + /// тип коллекции + public void AddCollection(string name, CollectionType collectionType) + { + CollectionInfo collectionInfo = new(name, collectionType, string.Empty); + if (name == null || _storages.ContainsKey(collectionInfo)) + return; + switch (collectionType) { - _storages = new Dictionary>(); - } - - /// - /// Добавление коллекции в хранилище - /// - /// Название коллекции - /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) - { - if (name == null || _storages.ContainsKey(name)) + case CollectionType.None: return; - - switch (collectionType) - { - case CollectionType.None: - return; - case CollectionType.Massive: - _storages[name] = new MassiveGenericObjects(); - return; - case CollectionType.List: - _storages[name] = new ListGenericObjects(); - return; - } - } - - /// - /// Удаление коллекции - /// - /// Название коллекции - public void DelCollection(string name) - { - if (_storages.ContainsKey(name)) - _storages.Remove(name); - } - - /// - /// Доступ к коллекции - /// - /// Название коллекции - /// - public ICollectionGenericObjects? this[string name] - { - get - { - if (name == null || !_storages.ContainsKey(name)) - return null; - - return _storages[name]; - } - } - - /// - /// Сохранение информации по самолетам в хранилище в файл - /// - /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public void SaveData(string filename) - { - if (_storages.Count == 0) - throw new NullReferenceException("В хранилище отсутствуют коллекции для сохранения"); - - if (File.Exists(filename)) - File.Delete(filename); - - - using (StreamWriter sw = new(filename)) - { - sw.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) - { - sw.Write(Environment.NewLine); - if (value.Value.Count == 0) - { - continue; - } - - sw.Write(value.Key); - sw.Write(_separatorForKeyValue); - sw.Write(value.Value.GetCollectionType); - sw.Write(_separatorForKeyValue); - sw.Write(value.Value.MaxCount); - sw.Write(_separatorForKeyValue); - - foreach (T? item in value.Value.GetItems()) - { - string data = item?.GetDataForSave() ?? string.Empty; - if (string.IsNullOrEmpty(data)) - { - continue; - } - - sw.Write(data); - sw.Write(_separatorItems); - } - } - } - } - - /// - /// Загрузка информации по самолетам в хранилище из файла - /// - /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public void LoadData(string filename) - { - if (!File.Exists(filename)) - { - throw new FileNotFoundException("Файл не существует"); - } - - using (StreamReader sr = new(filename)) - { - string str = sr.ReadLine(); - if (str == null || str.Length == 0) - { - throw new FileFormatException("В файле нет данных"); - } - - if (!str.Equals(_collectionKey)) - { - throw new FileFormatException("В файле неверные данные"); - } - _storages.Clear(); - - while (!sr.EndOfStream) - { - string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) - { - continue; - } - - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - throw new InvalidOperationException("Не удалось создать коллекцию"); - } - - collection.MaxCount = Convert.ToInt32(record[2]); - - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) - { - if (elem?.CreateDrawningCommonLiner() is T airplane) - { - try - { - if (collection.Insert(airplane) == -1) - throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); - } - catch (CollectionOverflowException ex) - { - throw new OverflowException("Коллекция переполнена", ex); - } - } - } - _storages.Add(record[0], collection); - } - } - } - - /// - /// Создание коллекции по типу - /// - /// - /// - private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) - { - return collectionType switch - { - CollectionType.Massive => new MassiveGenericObjects(), - CollectionType.List => new ListGenericObjects(), - _ => null, - }; + case CollectionType.Massive: + _storages[collectionInfo] = new MassiveGenericObjects(); + return; + case CollectionType.List: + _storages[collectionInfo] = new ListGenericObjects(); + return; + default: break; } } -} + + /// + /// Удаление коллекции + /// + /// Название коллекции + public void DelCollection(string name) + { + CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) + _storages.Remove(collectionInfo); + } + + /// + /// Доступ к коллекции + /// + /// Название коллекции + /// + public ICollectionGenericObjects? this[string name] + { + get + { + CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; + return null; + } + } + + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// + /// + public void SaveData(string filename) + { + if (_storages.Count == 0) + { + throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения"); + + } + if (File.Exists(filename)) + { + File.Delete(filename); + } + using (StreamWriter writer = new(filename)) + { + writer.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + writer.Write(Environment.NewLine); + // не сохраняем пустые коллекции + if (value.Value.Count == 0) + { + continue; + } + writer.Write(value.Key); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.MaxCount); + writer.Write(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + writer.Write(data); + writer.Write(_separatorItems); + } + } + } + } + + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// >Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public void LoadData(string filename) + { + if (!File.Exists(filename)) + { + throw new FileNotFoundException($"{filename} не существует"); + } + using (StreamReader reader = new(filename)) + { + string line = reader.ReadLine(); + if (line == null || line.Length == 0) + { + throw new FileFormatException("Файл не подходит"); + } + if (!line.Equals(_collectionKey)) + { + + throw new IOException("В файле неверные данные"); + } + _storages.Clear(); + while ((line = reader.ReadLine()) != null) + { + string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 3) + { + continue; + } + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new Exception("Не удалось определить информацию коллекции" + record[0]); + + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType); + if (collection == null) + { + throw new InvalidOperationException("Не удалось создать коллекцию"); + } + collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + if (elem?.CreateDrawningCommonLiner() is T truck) + { + try + { + if (collection.Insert(truck) == -1) + { + throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new DataException("Коллекция переполнена", ex); + } + } + } + _storages.Add(collectionInfo, collection); + } + } + } + + /// + /// Создание коллекции по типу + /// + /// + /// + private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) + { + return collectionType switch + { + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null, + }; + } +} \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/FormLinerCollection.cs b/ProjectLiner/ProjectLiner/FormLinerCollection.cs index ed4a241..5d88ee7 100644 --- a/ProjectLiner/ProjectLiner/FormLinerCollection.cs +++ b/ProjectLiner/ProjectLiner/FormLinerCollection.cs @@ -86,6 +86,11 @@ namespace ProjectLiner MessageBox.Show(ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (ObjectAlreadyExistsException ex) + { + MessageBox.Show("Такой объект есть в коллекции"); + _logger.LogWarning($"Добавление существующего объекта: {ex.Message}"); + } } /// @@ -240,7 +245,7 @@ namespace ProjectLiner listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; + string? colName = _storageCollection.Keys?[i].Name; if (!string.IsNullOrEmpty(colName)) listBoxCollection.Items.Add(colName); } -- 2.25.1