Menu
Coddy logo textTech
flag Ar iconالعربيةdown icon

الفراغ والحجم

جزء من قسم Logic & Flow في رحلة C# على Coddy — الدرس 60 من 66.

توفر الـ HashSets طرقاً للتحقق مما إذا كانت فارغة ولتحديد حجمها.

إنشاء HashSet فارغ

HashSet<string> colors = new HashSet<string>();

تحقق مما إذا كان HashSet فارغاً باستخدام Count

bool isEmpty = colors.Count == 0;
// isEmpty قيمتها true

أضف بعض العناصر إلى HashSet

colors.Add("Red");
colors.Add("Blue");
colors.Add("Green");

احصل على حجم الـ HashSet

int size = colors.Count;
// الحجم هو 3

يمكنك أيضاً التحقق مما إذا كان HashSet فارغاً باستخدام طريقة Any()

bool hasElements = colors.Any();
// hasElements قيمته true لأن المجموعة تحتوي على عناصر
challenge icon

التحدي

سهل

أنشئ طريقة تسمى CountAndCheck تأخذ HashSet من السلاسل النصية (strings) كمعامل. يجب أن تقوم الطريقة بما يلي:

  1. التحقق مما إذا كان HashSet فارغاً.
  2. طباعة "Empty set" إذا كان فارغاً.
  3. خلاف ذلك، طباعة "Set contains {count} elements" حيث {count} هو عدد العناصر في HashSet.

ورقة مرجعية

تحقق مما إذا كان الـ HashSet فارغاً باستخدام Count:

bool isEmpty = colors.Count == 0;

الحصول على حجم الـ HashSet:

int size = colors.Count;

تحقق مما إذا كان الـ HashSet يحتوي على عناصر باستخدام Any():

bool hasElements = colors.Any();

جرّب بنفسك

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static void CountAndCheck(HashSet<string> set)
    {
        // اكتب كودك هنا
    }
    
    static void Main(string[] args)
    {
        // قراءة المدخلات لعناصر HashSet مفصولة بفواصل
        // إذا كانت المدخلات فارغة، قم بإنشاء HashSet فارغة
        string input = Console.ReadLine();
        
        HashSet<string> set = new HashSet<string>();
        if (!string.IsNullOrEmpty(input))
        {
            string[] elements = input.Split(',');
            foreach (string element in elements)
            {
                set.Add(element.Trim());
            }
        }
        
        CountAndCheck(set);
    }
}
quiz iconاختبر نفسك

يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.

جميع دروس Logic & Flow