1
0
This commit is contained in:
Debug_pro
2026-06-07 18:27:45 +03:00
commit d47bde6c27
7 changed files with 1214 additions and 0 deletions

63
.gitattributes vendored Normal file
View File

@@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

363
.gitignore vendored Normal file
View File

@@ -0,0 +1,363 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd

88
GymEquipment.cs Normal file
View File

@@ -0,0 +1,88 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Prac8
{
public class GymEquipment : IComparable<GymEquipment>, IEquatable<GymEquipment>
{
public int Number { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string Condition { get; set; }
public string Place { get; set; }
public GymEquipment()
{
Name = string.Empty;
Type = string.Empty;
Condition = string.Empty;
Place = string.Empty;
}
public GymEquipment(int number, string name, string type, string condition, string place)
{
Number = number;
Name = name;
Type = type;
Condition = condition;
Place = place;
}
public int CompareTo(GymEquipment other)
{
if (other == null)
{
return 1;
}
int byName = string.Compare(Name, other.Name, StringComparison.OrdinalIgnoreCase);
if (byName != 0)
{
return byName;
}
return Number.CompareTo(other.Number);
}
public bool Equals(GymEquipment other)
{
if (other == null)
{
return false;
}
return Number == other.Number
&& string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(Type, other.Type, StringComparison.OrdinalIgnoreCase)
&& string.Equals(Condition, other.Condition, StringComparison.OrdinalIgnoreCase)
&& string.Equals(Place, other.Place, StringComparison.OrdinalIgnoreCase);
}
public override bool Equals(object obj)
{
return Equals(obj as GymEquipment);
}
public override int GetHashCode()
{
return GetSafeHash(Name)
^ GetSafeHash(Type)
^ GetSafeHash(Condition)
^ GetSafeHash(Place)
^ Number;
}
private static int GetSafeHash(string value)
{
return value == null ? 0 : value.ToLowerInvariant().GetHashCode();
}
public override string ToString()
{
return $"№: {Number}, Название: {Name}, Тип: {Type}, Состояние: {Condition}, Место: {Place}";
}
}
}

358
MyList.cs Normal file
View File

@@ -0,0 +1,358 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Prac8
{
public class MyList<T> : IEnumerable<T>
{
private const int DefaultCapacity = 4;
private T[] _items;
private int _count;
public MyList(int capacity = DefaultCapacity)
{
if (capacity < 1)
{
capacity = DefaultCapacity;
}
_items = new T[capacity];
_count = 0;
}
public int Count => _count;
public T this[int index]
{
get => Get(index);
set
{
ValidateIndex(index);
_items[index] = value;
}
}
public void Add(T item)
{
EnsureCapacity();
_items[_count] = item;
_count++;
}
public void Insert(int index, T item)
{
ValidateInsertIndex(index);
EnsureCapacity();
for (int i = _count; i > index; i--)
{
_items[i] = _items[i - 1];
}
_items[index] = item;
_count++;
}
public void AddRange(MyList<T> otherList)
{
if (otherList == null)
{
throw new ArgumentNullException(nameof(otherList), "Другой список не должен быть null.");
}
MyList<T> source = CreateSafeCopy(otherList);
EnsureCapacityFor(source.Count);
foreach (T item in source)
{
Add(item);
}
}
public void InsertRange(int index, MyList<T> otherList)
{
ValidateInsertIndex(index);
if (otherList == null)
{
throw new ArgumentNullException(nameof(otherList), "Другой список не должен быть null.");
}
if (otherList.Count == 0)
{
return;
}
MyList<T> source = CreateSafeCopy(otherList);
EnsureCapacityFor(source.Count);
for (int i = _count - 1; i >= index; i--)
{
_items[i + source.Count] = _items[i];
}
int insertPosition = index;
foreach (T item in source)
{
_items[insertPosition] = item;
insertPosition++;
}
_count += source.Count;
}
public void RemoveAt(int index)
{
ValidateIndex(index);
for (int i = index; i < _count - 1; i++)
{
_items[i] = _items[i + 1];
}
_count--;
_items[_count] = default(T);
}
public void RemoveLast()
{
if (_count == 0)
{
throw new InvalidOperationException("Нельзя удалить последний элемент из пустого списка.");
}
_count--;
_items[_count] = default(T);
}
public void RemoveRange(int firstIndex, int secondIndex)
{
if (_count == 0)
{
throw new InvalidOperationException("Список пуст.");
}
ValidateIndex(firstIndex);
ValidateIndex(secondIndex);
if (firstIndex > secondIndex)
{
throw new ArgumentException("Первый индекс не может быть больше второго.");
}
int removeCount = secondIndex - firstIndex + 1;
for (int i = firstIndex; i < _count - removeCount; i++)
{
_items[i] = _items[i + removeCount];
}
for (int i = _count - removeCount; i < _count; i++)
{
_items[i] = default(T);
}
_count -= removeCount;
}
public void Clear()
{
for (int i = 0; i < _count; i++)
{
_items[i] = default(T);
}
_count = 0;
}
public T Get(int index)
{
ValidateIndex(index);
return _items[index];
}
public void Print()
{
if (_count == 0)
{
Console.WriteLine("Список пуст.");
return;
}
for (int i = 0; i < _count; i++)
{
Console.WriteLine($"[{i}] {_items[i]}");
}
}
public T Find(Predicate<T> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match), "Предикат не должен быть null.");
}
for (int i = 0; i < _count; i++)
{
if (match(_items[i]))
{
return _items[i];
}
}
return default(T);
}
public void EnsureCapacity()
{
if (_count < _items.Length)
{
return;
}
int newCapacity = _items.Length == 0 ? DefaultCapacity : _items.Length * 2;
Array.Resize(ref _items, newCapacity);
}
public void Sort(int index)
{
if (index != 0 && index != 1)
{
throw new ArgumentException("Для сортировки используйте 1 - по возрастанию или 0 - по убыванию.");
}
if (_count < 2)
{
return;
}
Comparer<T> comparer = Comparer<T>.Default;
bool ascending = index == 1;
for (int i = 0; i < _count - 1; i++)
{
int selectedIndex = i;
for (int j = i + 1; j < _count; j++)
{
int compareResult = comparer.Compare(_items[j], _items[selectedIndex]);
if ((ascending && compareResult < 0) || (!ascending && compareResult > 0))
{
selectedIndex = j;
}
}
if (selectedIndex != i)
{
T temp = _items[i];
_items[i] = _items[selectedIndex];
_items[selectedIndex] = temp;
}
}
}
public void Reverse()
{
int left = 0;
int right = _count - 1;
while (left < right)
{
T temp = _items[left];
_items[left] = _items[right];
_items[right] = temp;
left++;
right--;
}
}
public void Distinct()
{
if (_count < 2)
{
return;
}
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
T[] uniqueItems = new T[Math.Max(DefaultCapacity, _count)];
int uniqueCount = 0;
for (int i = 0; i < _count; i++)
{
bool exists = false;
for (int j = 0; j < uniqueCount; j++)
{
if (comparer.Equals(_items[i], uniqueItems[j]))
{
exists = true;
break;
}
}
if (!exists)
{
uniqueItems[uniqueCount] = _items[i];
uniqueCount++;
}
}
_items = uniqueItems;
_count = uniqueCount;
}
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < _count; i++)
{
yield return _items[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private void ValidateIndex(int index)
{
if (index < 0 || index >= _count)
{
throw new IndexOutOfRangeException("Индекс находится вне границ списка.");
}
}
private void ValidateInsertIndex(int index)
{
if (index < 0 || index > _count)
{
throw new IndexOutOfRangeException("Индекс для вставки находится вне границ списка.");
}
}
private void EnsureCapacityFor(int additionalItems)
{
while (_count + additionalItems > _items.Length)
{
int newCapacity = _items.Length == 0 ? DefaultCapacity : _items.Length * 2;
Array.Resize(ref _items, newCapacity);
}
}
private static MyList<T> CreateSafeCopy(MyList<T> source)
{
MyList<T> copy = new MyList<T>(Math.Max(DefaultCapacity, source.Count));
foreach (T item in source)
{
copy.Add(item);
}
return copy;
}
}
}

10
Prac8.csproj Normal file
View File

@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

25
Prac8.sln Normal file
View File

@@ -0,0 +1,25 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36429.23 d17.14
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Prac8", "Prac8.csproj", "{7B2E7D89-B72B-437B-8ADB-27901B43B4B8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7B2E7D89-B72B-437B-8ADB-27901B43B4B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7B2E7D89-B72B-437B-8ADB-27901B43B4B8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7B2E7D89-B72B-437B-8ADB-27901B43B4B8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7B2E7D89-B72B-437B-8ADB-27901B43B4B8}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {CEBDCD76-826A-4855-873E-397E0F7768EC}
EndGlobalSection
EndGlobal

307
Program.cs Normal file
View File

@@ -0,0 +1,307 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Prac8
{
internal class Program
{
private static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
MyList<GymEquipment> equipmentList = new MyList<GymEquipment>();
bool isRunning = true;
while (isRunning)
{
PrintMenu();
Console.Write("Выберите действие: ");
string choice = Console.ReadLine();
Console.WriteLine();
try
{
switch (choice)
{
case "1":
equipmentList.Add(ReadEquipment());
Console.WriteLine("Тренажёр добавлен в конец списка.");
break;
case "2":
{
int index = ReadInt("Введите индекс для вставки: ");
equipmentList.Insert(index, ReadEquipment());
Console.WriteLine("Тренажёр вставлен по указанному индексу.");
break;
}
case "3":
{
int index = ReadInt("Введите индекс изменяемого элемента: ");
equipmentList[index] = ReadEquipment();
Console.WriteLine("Элемент успешно изменён.");
break;
}
case "4":
equipmentList.RemoveLast();
Console.WriteLine("Последний элемент удалён.");
break;
case "5":
{
int index = ReadInt("Введите индекс удаляемого элемента: ");
equipmentList.RemoveAt(index);
Console.WriteLine("Элемент удалён.");
break;
}
case "6":
Console.WriteLine($"Количество элементов: {equipmentList.Count}");
break;
case "7":
equipmentList.Print();
break;
case "8":
{
int index = ReadInt("Введите индекс элемента: ");
Console.WriteLine(equipmentList.Get(index));
break;
}
case "9":
AddRangeInteractive(equipmentList);
break;
case "10":
InsertRangeInteractive(equipmentList);
break;
case "11":
{
int firstIndex = ReadInt("Введите первый индекс: ");
int secondIndex = ReadInt("Введите второй индекс: ");
equipmentList.RemoveRange(firstIndex, secondIndex);
Console.WriteLine("Диапазон элементов удалён.");
break;
}
case "12":
FindEquipment(equipmentList);
break;
case "13":
{
int sortMode = ReadInt("Введите 1 для сортировки по возрастанию или 0 для сортировки по убыванию: ");
equipmentList.Sort(sortMode);
Console.WriteLine("Список отсортирован.");
break;
}
case "14":
equipmentList.Reverse();
Console.WriteLine("Список развёрнут.");
break;
case "15":
equipmentList.Distinct();
Console.WriteLine("Дубликаты удалены.");
break;
case "16":
equipmentList.Clear();
Console.WriteLine("Список очищен.");
break;
case "17":
PrintWithForeach(equipmentList);
break;
case "0":
isRunning = false;
Console.WriteLine("Программа завершена.");
break;
default:
Console.WriteLine("Такого пункта меню нет. Люди, как обычно, выбирают что попало.");
break;
}
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка: {ex.Message}");
}
if (isRunning)
{
Pause();
Console.Clear();
}
}
}
private static void PrintMenu()
{
Console.WriteLine("Меню работы с MyList<Тренажёр>:");
Console.WriteLine("1 - Добавить элемент в конец");
Console.WriteLine("2 - Добавить элемент по индексу");
Console.WriteLine("3 - Изменить элемент по индексу");
Console.WriteLine("4 - Удалить последний элемент");
Console.WriteLine("5 - Удалить элемент по индексу");
Console.WriteLine("6 - Получить количество элементов");
Console.WriteLine("7 - Вывести список");
Console.WriteLine("8 - Вывести элемент по индексу");
Console.WriteLine("9 - Добавить диапазон элементов в конец");
Console.WriteLine("10 - Вставить диапазон элементов по индексу");
Console.WriteLine("11 - Удалить диапазон элементов");
Console.WriteLine("12 - Найти элемент по условию");
Console.WriteLine("13 - Сортировать список");
Console.WriteLine("14 - Развернуть список");
Console.WriteLine("15 - Удалить дубликаты");
Console.WriteLine("16 - Очистить список");
Console.WriteLine("17 - Вывести список через foreach");
Console.WriteLine("0 - Выход");
Console.WriteLine();
}
private static GymEquipment ReadEquipment()
{
Console.WriteLine("Введите данные тренажёра:");
int number = ReadInt("№: ");
string name = ReadRequiredString("Название: ");
string type = ReadRequiredString("Тип: ");
string condition = ReadRequiredString("Состояние: ");
string place = ReadRequiredString("Место: ");
return new GymEquipment(number, name, type, condition, place);
}
private static void AddRangeInteractive(MyList<GymEquipment> equipmentList)
{
int count = ReadInt("Сколько элементов нужно добавить в конец: ");
if (count <= 0)
{
Console.WriteLine("Количество должно быть больше нуля.");
return;
}
MyList<GymEquipment> tempList = new MyList<GymEquipment>(count);
for (int i = 0; i < count; i++)
{
Console.WriteLine($"\nЭлемент {i + 1} из {count}:");
tempList.Add(ReadEquipment());
}
equipmentList.AddRange(tempList);
Console.WriteLine("Диапазон элементов добавлен в конец списка.");
}
private static void InsertRangeInteractive(MyList<GymEquipment> equipmentList)
{
int index = ReadInt("Введите индекс для вставки диапазона: ");
int count = ReadInt("Сколько элементов нужно вставить: ");
if (count <= 0)
{
Console.WriteLine("Количество должно быть больше нуля.");
return;
}
MyList<GymEquipment> tempList = new MyList<GymEquipment>(count);
for (int i = 0; i < count; i++)
{
Console.WriteLine($"\nЭлемент {i + 1} из {count}:");
tempList.Add(ReadEquipment());
}
equipmentList.InsertRange(index, tempList);
Console.WriteLine("Диапазон элементов вставлен.");
}
private static void FindEquipment(MyList<GymEquipment> equipmentList)
{
if (equipmentList.Count == 0)
{
Console.WriteLine("Список пуст.");
return;
}
string fragment = ReadRequiredString("Введите текст для поиска (по названию, типу, состоянию или месту): ");
GymEquipment found = equipmentList.Find(item =>
item.Name.IndexOf(fragment, StringComparison.OrdinalIgnoreCase) >= 0
|| item.Type.IndexOf(fragment, StringComparison.OrdinalIgnoreCase) >= 0
|| item.Condition.IndexOf(fragment, StringComparison.OrdinalIgnoreCase) >= 0
|| item.Place.IndexOf(fragment, StringComparison.OrdinalIgnoreCase) >= 0);
if (found == null)
{
Console.WriteLine("Подходящий элемент не найден.");
}
else
{
Console.WriteLine("Найденный элемент:");
Console.WriteLine(found);
}
}
private static void PrintWithForeach(MyList<GymEquipment> equipmentList)
{
if (equipmentList.Count == 0)
{
Console.WriteLine("Список пуст.");
return;
}
int index = 0;
foreach (GymEquipment equipment in equipmentList)
{
Console.WriteLine($"[{index}] {equipment}");
index++;
}
}
private static int ReadInt(string message)
{
while (true)
{
Console.Write(message);
string input = Console.ReadLine();
if (int.TryParse(input, out int value))
{
return value;
}
Console.WriteLine("Введите целое число.");
}
}
private static string ReadRequiredString(string message)
{
while (true)
{
Console.Write(message);
string input = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(input))
{
return input.Trim();
}
Console.WriteLine("Строка не должна быть пустой.");
}
}
private static void Pause()
{
Console.WriteLine();
Console.WriteLine("Нажмите Enter, чтобы продолжить...");
Console.ReadLine();
}
}
}