کار با فایلها و Collections 📁📊
چطوری دادهها رو ذخیره کنیم و با مجموعهها کار کنیم؟
کار با فایلها در C# 📁
در C# برای کار با فایلها از namespace System.IO استفاده میکنیم. این namespace شامل کلاسهای مختلفی برای خواندن، نوشتن، کپی، حذف و مدیریت فایلها و پوشهها است.
کلاس File و متدهای مهم آن
📖 خواندن فایل
- •
File.ReadAllText()- خواندن کل فایل - •
File.ReadAllLines()- خواندن خط به خط - •
File.ReadAllBytes()- خواندن باینری
✏️ نوشتن فایل
- •
File.WriteAllText()- نوشتن متن - •
File.WriteAllLines()- نوشتن خطوط - •
File.AppendAllText()- اضافه کردن
🔧 مدیریت فایل
- •
File.Exists()- بررسی وجود - •
File.Copy()- کپی کردن - •
File.Delete()- حذف کردن
📊 اطلاعات فایل
- •
File.GetCreationTime()- زمان ایجاد - •
File.GetLastWriteTime()- آخرین تغییر - •
new FileInfo().Length- اندازه فایل
کلاسهای Stream برای کار پیشرفته
برای فایلهای بزرگ یا کنترل بیشتر روی عملیات، از کلاسهای Stream استفاده میکنیم:
using System;
using System.IO;
class FileStreamExample
{
static void Main()
{
string filePath = "example.txt";
// نوشتن با StreamWriter
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("خط اول فایل");
writer.WriteLine("خط دوم فایل");
writer.WriteLine($"زمان ایجاد: {DateTime.Now}");
}
Console.WriteLine("✅ فایل ایجاد شد!");
// خواندن با StreamReader
using (StreamReader reader = new StreamReader(filePath))
{
string line;
int lineNumber = 1;
Console.WriteLine("📖 محتوای فایل:");
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine($"{lineNumber}: {line}");
lineNumber++;
}
}
// نمایش اطلاعات فایل
FileInfo fileInfo = new FileInfo(filePath);
Console.WriteLine($"\n📊 اطلاعات فایل:");
Console.WriteLine($"اندازه: {fileInfo.Length} بایت");
Console.WriteLine($"ایجاد شده: {fileInfo.CreationTime}");
Console.WriteLine($"آخرین تغییر: {fileInfo.LastWriteTime}");
}
}
Collections در C# 📚
Collections مجموعهای از کلاسها هستند که در namespace System.Collections.Generic قرار دارند و برای ذخیره، مدیریت و دستکاری گروهی از اشیاء استفاده میشوند.
📋 List<T> - لیست پویا
List یک آرایه پویا است که میتواند در زمان اجرا رشد یا کوچک شود.
➕ اضافه کردن
- •
Add()- اضافه کردن یک آیتم - •
AddRange()- اضافه کردن چند آیتم - •
Insert()- درج در موقعیت خاص
➖ حذف کردن
- •
Remove()- حذف آیتم مشخص - •
RemoveAt()- حذف با ایندکس - •
Clear()- پاک کردن همه
🔍 جستجو
- •
Contains()- بررسی وجود - •
IndexOf()- پیدا کردن ایندکس - •
Find()- جستجو با شرط
🗂️ Dictionary<TKey, TValue> - فرهنگ لغت
Dictionary مجموعهای از جفت کلید-مقدار است که دسترسی سریع به دادهها را فراهم میکند.
🔑 کار با کلیدها
- •
Add(key, value)- اضافه کردن - •
ContainsKey()- بررسی کلید - •
Keys- دریافت کلیدها
💎 کار با مقادیر
- •
dict[key]- دسترسی به مقدار - •
TryGetValue()- دریافت ایمن - •
Values- دریافت مقادیر
🎯 سایر Collections مهم
📚 HashSet<T>
مجموعهای از آیتمهای یکتا (بدون تکرار)
- •
Add()- اضافه کردن یکتا - •
UnionWith()- اجتماع - •
IntersectWith()- اشتراک
🔄 Queue<T> و Stack<T>
صف (FIFO) و پشته (LIFO)
- •
Enqueue()/Push()- اضافه کردن - •
Dequeue()/Pop()- برداشتن - •
Peek()- مشاهده بدون برداشت
مثالهای عملی 💡
📁 مثال کامل: مدیریت فایلهای متنی
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class NoteManager
{
private string notesDirectory = "Notes";
public NoteManager()
{
// ایجاد پوشه یادداشتها اگر وجود نداشته باشد
if (!Directory.Exists(notesDirectory))
{
Directory.CreateDirectory(notesDirectory);
Console.WriteLine($"📁 پوشه {notesDirectory} ایجاد شد.");
}
}
// ایجاد یادداشت جدید
public void CreateNote(string title, string content)
{
string fileName = $"{title.Replace(" ", "_")}.txt";
string filePath = Path.Combine(notesDirectory, fileName);
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine($"عنوان: {title}");
writer.WriteLine($"تاریخ ایجاد: {DateTime.Now}");
writer.WriteLine(new string('-', 40));
writer.WriteLine(content);
}
Console.WriteLine($"✅ یادداشت '{title}' ایجاد شد.");
}
catch (Exception ex)
{
Console.WriteLine($"❌ خطا در ایجاد یادداشت: {ex.Message}");
}
}
// خواندن یادداشت
public void ReadNote(string title)
{
string fileName = $"{title.Replace(" ", "_")}.txt";
string filePath = Path.Combine(notesDirectory, fileName);
if (File.Exists(filePath))
{
Console.WriteLine($"\n📖 محتوای یادداشت '{title}':");
Console.WriteLine(new string('=', 50));
string[] lines = File.ReadAllLines(filePath);
foreach (string line in lines)
{
Console.WriteLine(line);
}
Console.WriteLine(new string('=', 50));
}
else
{
Console.WriteLine($"❌ یادداشت '{title}' پیدا نشد.");
}
}
// لیست تمام یادداشتها
public void ListAllNotes()
{
string[] files = Directory.GetFiles(notesDirectory, "*.txt");
if (files.Length == 0)
{
Console.WriteLine("📝 هیچ یادداشتی وجود ندارد.");
return;
}
Console.WriteLine($"\n📋 لیست یادداشتها ({files.Length} عدد):");
for (int i = 0; i < files.Length; i++)
{
string fileName = Path.GetFileNameWithoutExtension(files[i]);
FileInfo fileInfo = new FileInfo(files[i]);
Console.WriteLine($"{i + 1}. {fileName.Replace("_", " ")} - {fileInfo.LastWriteTime:yyyy/MM/dd HH:mm}");
}
}
// جستجو در یادداشتها
public void SearchNotes(string keyword)
{
string[] files = Directory.GetFiles(notesDirectory, "*.txt");
List foundNotes = new List();
foreach (string file in files)
{
string content = File.ReadAllText(file);
if (content.Contains(keyword, StringComparison.OrdinalIgnoreCase))
{
foundNotes.Add(Path.GetFileNameWithoutExtension(file).Replace("_", " "));
}
}
if (foundNotes.Count > 0)
{
Console.WriteLine($"\n🔍 یادداشتهای حاوی '{keyword}' ({foundNotes.Count} عدد):");
foreach (string note in foundNotes)
{
Console.WriteLine($" - {note}");
}
}
else
{
Console.WriteLine($"❌ هیچ یادداشتی حاوی '{keyword}' پیدا نشد.");
}
}
}
📚 مثال کامل: سیستم مدیریت محصولات
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public int Stock { get; set; }
public DateTime AddedDate { get; set; }
}
class OnlineStore
{
private List products;
private Dictionary> categoryIndex;
private HashSet categories;
private Queue recentSearches;
private Stack actionHistory;
public OnlineStore()
{
products = new List();
categoryIndex = new Dictionary>();
categories = new HashSet();
recentSearches = new Queue();
actionHistory = new Stack();
}
// اضافه کردن محصول
public void AddProduct(string name, decimal price, string category, int stock)
{
var product = new Product
{
Id = products.Count + 1,
Name = name,
Price = price,
Category = category,
Stock = stock,
AddedDate = DateTime.Now
};
products.Add(product);
categories.Add(category);
// بهروزرسانی ایندکس دستهبندی
if (!categoryIndex.ContainsKey(category))
{
categoryIndex[category] = new List();
}
categoryIndex[category].Add(product);
actionHistory.Push($"محصول '{name}' اضافه شد");
Console.WriteLine($"✅ محصول '{name}' با موفقیت اضافه شد.");
}
// جستجوی محصول
public void SearchProducts(string keyword)
{
recentSearches.Enqueue(keyword);
if (recentSearches.Count > 5) // نگه داشتن آخرین 5 جستجو
{
recentSearches.Dequeue();
}
var results = products.Where(p =>
p.Name.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
p.Category.Contains(keyword, StringComparison.OrdinalIgnoreCase)
).ToList();
Console.WriteLine($"\n🔍 نتایج جستجو برای '{keyword}' ({results.Count} محصول):");
foreach (var product in results)
{
Console.WriteLine($" {product.Id}. {product.Name} - {product.Price:N0} تومان ({product.Category})");
}
}
// نمایش محصولات بر اساس دستهبندی
public void ShowProductsByCategory()
{
Console.WriteLine("\n📊 محصولات بر اساس دستهبندی:");
foreach (var category in categories.OrderBy(c => c))
{
var categoryProducts = categoryIndex[category];
Console.WriteLine($"\n🏷️ {category} ({categoryProducts.Count} محصول):");
foreach (var product in categoryProducts.OrderBy(p => p.Price))
{
string stockStatus = product.Stock > 0 ? $"({product.Stock} عدد)" : "(ناموجود)";
Console.WriteLine($" - {product.Name}: {product.Price:N0} تومان {stockStatus}");
}
}
}
// آمار فروشگاه
public void ShowStatistics()
{
Console.WriteLine("\n📈 آمار فروشگاه:");
Console.WriteLine($" 📦 تعداد کل محصولات: {products.Count}");
Console.WriteLine($" 🏷️ تعداد دستهبندیها: {categories.Count}");
Console.WriteLine($" 💰 گرانترین محصول: {products.Max(p => p.Price):N0} تومان");
Console.WriteLine($" 💸 ارزانترین محصول: {products.Min(p => p.Price):N0} تومان");
Console.WriteLine($" 📊 میانگین قیمت: {products.Average(p => p.Price):N0} تومان");
// نمایش آخرین جستجوها
if (recentSearches.Count > 0)
{
Console.WriteLine($"\n🔍 آخرین جستجوها:");
foreach (string search in recentSearches)
{
Console.WriteLine($" - {search}");
}
}
// نمایش تاریخچه عملیات
if (actionHistory.Count > 0)
{
Console.WriteLine($"\n📋 آخرین عملیات:");
var recentActions = actionHistory.Take(3);
foreach (string action in recentActions)
{
Console.WriteLine($" - {action}");
}
}
}
// ذخیره در فایل JSON
public void SaveToFile(string fileName = "products.json")
{
try
{
string json = JsonSerializer.Serialize(products, new JsonSerializerOptions
{
WriteIndented = true,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
});
File.WriteAllText(fileName, json);
Console.WriteLine($"✅ اطلاعات در فایل {fileName} ذخیره شد.");
}
catch (Exception ex)
{
Console.WriteLine($"❌ خطا در ذخیره فایل: {ex.Message}");
}
}
}
🚀 برنامه اصلی
class Program
{
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
// تست سیستم مدیریت یادداشتها
Console.WriteLine("=== سیستم مدیریت یادداشتها ===");
NoteManager noteManager = new NoteManager();
noteManager.CreateNote("لیست خرید", "شیر\nنان\nتخم مرغ\nسیب");
noteManager.CreateNote("ایده پروژه", "ساخت اپلیکیشن مدیریت وقت\nاستفاده از C# و WPF");
noteManager.ListAllNotes();
noteManager.SearchNotes("اپلیکیشن");
noteManager.ReadNote("لیست خرید");
Console.WriteLine("\n" + new string('=', 60) + "\n");
// تست فروشگاه آنلاین
Console.WriteLine("=== فروشگاه آنلاین ===");
OnlineStore store = new OnlineStore();
// اضافه کردن محصولات
store.AddProduct("لپتاپ ایسوس", 15000000, "الکترونیک", 5);
store.AddProduct("کتاب برنامهنویسی C#", 120000, "کتاب", 10);
store.AddProduct("موبایل سامسونگ", 8000000, "الکترونیک", 3);
store.AddProduct("کتاب ریاضی", 80000, "کتاب", 7);
store.AddProduct("هدفون بلوتوثی", 500000, "الکترونیک", 12);
// عملیات مختلف
store.SearchProducts("کتاب");
store.ShowProductsByCategory();
store.ShowStatistics();
store.SaveToFile();
Console.WriteLine("\n🎉 برنامه با موفقیت اجرا شد!");
Console.ReadKey();
}
}
تمرینهای عملی 💪
📝 تمرین ۱: سیستم مدیریت دانشجویان
یک برنامه کامل برای مدیریت اطلاعات دانشجویان بنویسید که شامل موارد زیر باشد:
- کلاس
Studentبا خصوصیات: شماره دانشجویی، نام، رشته، نمرات (List<double>) - کلاس
StudentManagerبرای مدیریت دانشجویان با Dictionary - قابلیت اضافه کردن، حذف، جستجو و ویرایش دانشجو
- محاسبه معدل هر دانشجو و کل کلاس
- ذخیره و بارگذاری از فایل JSON
- گزارشگیری (بهترین دانشجو، آمار رشتهها، و...)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
class Student
{
public string StudentId { get; set; }
public string Name { get; set; }
public string Major { get; set; }
public List Grades { get; set; } = new List();
public double CalculateAverage()
{
return Grades.Count > 0 ? Grades.Average() : 0;
}
public string GetGradeStatus()
{
double avg = CalculateAverage();
if (avg >= 17) return "عالی";
if (avg >= 14) return "خوب";
if (avg >= 12) return "متوسط";
if (avg >= 10) return "قابل قبول";
return "مردود";
}
}
class StudentManager
{
private Dictionary students;
private string dataFile = "students.json";
public StudentManager()
{
students = new Dictionary();
LoadFromFile();
}
// اضافه کردن دانشجو
public bool AddStudent(string id, string name, string major)
{
if (students.ContainsKey(id))
{
Console.WriteLine($"❌ دانشجو با شماره {id} قبلاً وجود دارد.");
return false;
}
students[id] = new Student
{
StudentId = id,
Name = name,
Major = major
};
Console.WriteLine($"✅ دانشجو {name} اضافه شد.");
return true;
}
// اضافه کردن نمره
public bool AddGrade(string studentId, double grade)
{
if (!students.ContainsKey(studentId))
{
Console.WriteLine($"❌ دانشجو با شماره {studentId} پیدا نشد.");
return false;
}
if (grade < 0 || grade > 20)
{
Console.WriteLine("❌ نمره باید بین 0 تا 20 باشد.");
return false;
}
students[studentId].Grades.Add(grade);
Console.WriteLine($"✅ نمره {grade} برای دانشجو {studentId} اضافه شد.");
return true;
}
// جستجوی دانشجو
public void SearchStudent(string keyword)
{
var results = students.Values.Where(s =>
s.Name.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
s.StudentId.Contains(keyword) ||
s.Major.Contains(keyword, StringComparison.OrdinalIgnoreCase)
).ToList();
if (results.Count == 0)
{
Console.WriteLine($"❌ هیچ دانشجویی با کلیدواژه '{keyword}' پیدا نشد.");
return;
}
Console.WriteLine($"\n🔍 نتایج جستجو برای '{keyword}' ({results.Count} دانشجو):");
foreach (var student in results)
{
Console.WriteLine($" {student.StudentId} - {student.Name} ({student.Major}) - معدل: {student.CalculateAverage():F2}");
}
}
// نمایش آمار کلی
public void ShowStatistics()
{
if (students.Count == 0)
{
Console.WriteLine("❌ هیچ دانشجویی ثبت نشده است.");
return;
}
Console.WriteLine("\n📊 آمار کلی:");
Console.WriteLine($" 👥 تعداد دانشجویان: {students.Count}");
var studentsWithGrades = students.Values.Where(s => s.Grades.Count > 0).ToList();
if (studentsWithGrades.Count > 0)
{
double classAverage = studentsWithGrades.Average(s => s.CalculateAverage());
Console.WriteLine($" 📈 معدل کل کلاس: {classAverage:F2}");
var topStudent = studentsWithGrades.OrderByDescending(s => s.CalculateAverage()).First();
Console.WriteLine($" 🏆 بهترین دانشجو: {topStudent.Name} (معدل: {topStudent.CalculateAverage():F2})");
}
// آمار رشتهها
var majorStats = students.Values.GroupBy(s => s.Major)
.ToDictionary(g => g.Key, g => g.Count());
Console.WriteLine("\n🎓 آمار رشتهها:");
foreach (var major in majorStats)
{
Console.WriteLine($" {major.Key}: {major.Value} دانشجو");
}
}
// ذخیره در فایل
public void SaveToFile()
{
try
{
var studentList = students.Values.ToList();
string json = JsonSerializer.Serialize(studentList, new JsonSerializerOptions
{
WriteIndented = true,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
});
File.WriteAllText(dataFile, json);
Console.WriteLine($"✅ اطلاعات در فایل {dataFile} ذخیره شد.");
}
catch (Exception ex)
{
Console.WriteLine($"❌ خطا در ذخیره فایل: {ex.Message}");
}
}
// بارگذاری از فایل
private void LoadFromFile()
{
try
{
if (File.Exists(dataFile))
{
string json = File.ReadAllText(dataFile);
var studentList = JsonSerializer.Deserialize>(json);
students.Clear();
foreach (var student in studentList)
{
students[student.StudentId] = student;
}
Console.WriteLine($"✅ {studentList.Count} دانشجو از فایل بارگذاری شد.");
}
}
catch (Exception ex)
{
Console.WriteLine($"❌ خطا در بارگذاری فایل: {ex.Message}");
}
}
}
📚 تمرین ۲: سیستم مدیریت کتابخانه پیشرفته
یک سیستم کامل مدیریت کتابخانه طراحی کنید که شامل موارد زیر باشد:
- کلاسهای
Book،Member، وBorrowRecord - استفاده از Collections مختلف: List، Dictionary، HashSet، Queue
- سیستم امانت و بازگشت کتاب با تاریخگذاری
- محاسبه جریمه برای تأخیر در بازگشت
- سیستم رزرو کتاب (Queue)
- گزارشگیری کامل و آمارگیری
- ذخیرهسازی در فایلهای مختلف (JSON، CSV، TXT)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
class Book
{
public string ISBN { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string Category { get; set; }
public bool IsAvailable { get; set; } = true;
public DateTime PublishDate { get; set; }
}
class Member
{
public string MemberId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public DateTime JoinDate { get; set; }
public List BorrowHistory { get; set; } = new List();
}
class BorrowRecord
{
public string RecordId { get; set; }
public string MemberId { get; set; }
public string ISBN { get; set; }
public DateTime BorrowDate { get; set; }
public DateTime DueDate { get; set; }
public DateTime? ReturnDate { get; set; }
public decimal Fine { get; set; } = 0;
}
class LibraryManager
{
private Dictionary books;
private Dictionary members;
private List borrowRecords;
private Dictionary> reservations; // ISBN -> Queue of MemberIds
private HashSet categories;
private const decimal DAILY_FINE = 1000; // 1000 تومان در روز
private const int BORROW_PERIOD_DAYS = 14;
public LibraryManager()
{
books = new Dictionary();
members = new Dictionary();
borrowRecords = new List();
reservations = new Dictionary>();
categories = new HashSet();
LoadAllData();
}
// اضافه کردن کتاب
public bool AddBook(string isbn, string title, string author, string category)
{
if (books.ContainsKey(isbn))
{
Console.WriteLine($"❌ کتاب با ISBN {isbn} قبلاً وجود دارد.");
return false;
}
books[isbn] = new Book
{
ISBN = isbn,
Title = title,
Author = author,
Category = category,
PublishDate = DateTime.Now
};
categories.Add(category);
Console.WriteLine($"✅ کتاب '{title}' اضافه شد.");
return true;
}
// اضافه کردن عضو
public bool AddMember(string memberId, string name, string email)
{
if (members.ContainsKey(memberId))
{
Console.WriteLine($"❌ عضو با شناسه {memberId} قبلاً وجود دارد.");
return false;
}
members[memberId] = new Member
{
MemberId = memberId,
Name = name,
Email = email,
JoinDate = DateTime.Now
};
Console.WriteLine($"✅ عضو '{name}' اضافه شد.");
return true;
}
// امانت کتاب
public bool BorrowBook(string memberId, string isbn)
{
if (!members.ContainsKey(memberId))
{
Console.WriteLine($"❌ عضو با شناسه {memberId} پیدا نشد.");
return false;
}
if (!books.ContainsKey(isbn))
{
Console.WriteLine($"❌ کتاب با ISBN {isbn} پیدا نشد.");
return false;
}
var book = books[isbn];
if (!book.IsAvailable)
{
// اضافه کردن به صف رزرو
if (!reservations.ContainsKey(isbn))
{
reservations[isbn] = new Queue();
}
if (!reservations[isbn].Contains(memberId))
{
reservations[isbn].Enqueue(memberId);
Console.WriteLine($"📋 شما در صف رزرو کتاب '{book.Title}' قرار گرفتید. موقعیت: {reservations[isbn].Count}");
}
else
{
Console.WriteLine($"❌ شما قبلاً در صف رزرو این کتاب هستید.");
}
return false;
}
// ایجاد رکورد امانت
var record = new BorrowRecord
{
RecordId = Guid.NewGuid().ToString(),
MemberId = memberId,
ISBN = isbn,
BorrowDate = DateTime.Now,
DueDate = DateTime.Now.AddDays(BORROW_PERIOD_DAYS)
};
borrowRecords.Add(record);
book.IsAvailable = false;
members[memberId].BorrowHistory.Add(isbn);
Console.WriteLine($"✅ کتاب '{book.Title}' به {members[memberId].Name} امانت داده شد.");
Console.WriteLine($"📅 تاریخ بازگشت: {record.DueDate:yyyy/MM/dd}");
return true;
}
}
🎯 تمرین ساده: مدیریت محصولات
یک برنامه ساده بنویسید که لیستی از محصولات (نام، قیمت، دستهبندی) ایجاد کند، آنها را در فایل JSON ذخیره کند، سپس محصولات بالای قیمت مشخص را نمایش دهد.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
class Program
{
static void Main()
{
// ایجاد لیست محصولات
List products = new List
{
new Product { Name = "لپتاپ", Price = 15000000, Category = "الکترونیک" },
new Product { Name = "موس", Price = 50000, Category = "الکترونیک" },
new Product { Name = "کیبورد", Price = 150000, Category = "الکترونیک" },
new Product { Name = "مانیتور", Price = 8000000, Category = "الکترونیک" },
new Product { Name = "کتاب", Price = 80000, Category = "آموزش" }
};
// تبدیل به JSON و ذخیره در فایل
string jsonString = JsonSerializer.Serialize(products, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText("products.json", jsonString);
Console.WriteLine("محصولات در فایل ذخیره شدند! 💾");
// خواندن از فایل
string readJson = File.ReadAllText("products.json");
List loadedProducts = JsonSerializer.Deserialize>(readJson);
// فیلتر محصولات گران
decimal minPrice = 100000;
var expensiveProducts = loadedProducts.Where(p => p.Price > minPrice).ToList();
Console.WriteLine($"\nمحصولات بالای {minPrice:N0} تومان:");
foreach (var product in expensiveProducts)
{
Console.WriteLine($"- {product.Name}: {product.Price:N0} تومان ({product.Category})");
}
Console.ReadKey();
}
}
💡 نکات مهم برای حل تمرینها
- طراحی کلاسها: ابتدا کلاسهای مورد نیاز را با خصوصیات و متدهای مناسب طراحی کنید
- انتخاب Collection مناسب: برای هر نوع داده از Collection مناسب استفاده کنید (List، Dictionary، HashSet، Queue، Stack)
- مدیریت خطا: همیشه ورودیها را بررسی کنید و پیامهای مناسب نمایش دهید
- ذخیرهسازی: از JSON برای ذخیره دادههای پیچیده و CSV برای گزارشهای ساده استفاده کنید
- عملکرد: برای جستجوهای مکرر از Dictionary و HashSet استفاده کنید
- تست: هر قسمت را جداگانه تست کنید و سپس کل سیستم را آزمایش کنید