الأحد، 26 أكتوبر 2014

C# - List

C# - List

List هي مجموعة collection, وهي ليست ثابتة الحجم مثل الـ Array, ولا تحتاج الـ List إلى إدارة حجمهامثل الـ Array فعند تعريف Array دون تحديد حجمها سوف يظهر الخطأ.

Error     1          Array creation must have array size or array initializer

string[] arr = new string[];

لذلك فالــ Array  ذات حجم ثابت أما الـList  فهي علي العكس لا تحتاج لذلك فهي ديناميكية الحجم مع العديد من الإجراءات Method. حتى وإن تم تعريف حجم للـ List.

الـ List تتعامل مع اي نوع من البيانات Data Type.

تعريف List

لنتمكن من استخدام الـ List لابد من استدعاء namespace

using System.Collections.Generic;


أشكال الـ List


List<int> degree = new List<int>();
List<string> Names = new List<string>();
List<Customer> customerList = new List<Customer>();
List<int> list = new List<int>();
list.Add(2);
list.Add(3);
list.Add(5);

list.Add(7);


هنا تعريف List ذات حجم ثابت 2, ولكن تذكر ان هذا الحجم لا تأخذ به الـ List و تتجاهله سوف نعطي مثال.

List<Employee> EmpList = new List<Employee>(2);

يمكن تعريف List باي نوع من أنواع البيانات Date Type int, string, doube, decimal أو أنواع مركبcomplex  مثل  class أو struct.


استخدام Add Method

يتم إضافة عنصر داخل الـ List باستخدم Method Add.

مثال,
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 1, Name = "Slah", Balance = 5200 };
            Customer customer2 = new Customer() { ID = 2, Name = "Nasr", Balance = 3500 };
            Customer customer3 = new Customer() { ID = 3, Name = "Mona", Balance = 1700 };

            List<Customer> customerList = new List<Customer>(2);
            customerList.Add(customer1);
            customerList.Add(customer2);
            customerList.Add(customer3);   
        }
        public class Customer
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public double Balance { get; set; }
        }
    }
}

لاسترجعاع اي Item من الـ List يتم ذلك باستخدام الفهرس Index

مثال,
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 1, Name = "Slah", Balance = 5200 };
            Customer customer2 = new Customer() { ID = 2, Name = "Nasr", Balance = 3500 };
            Customer customer3 = new Customer() { ID = 3, Name = "Mona", Balance = 1700 };

            List<Customer> customerList = new List<Customer>(2);
            customerList.Add(customer1);
            customerList.Add(customer2);
            customerList.Add(customer3);
           
            // Retrieve item by index
            Customer c = customerList[2];
            Console.WriteLine("Id = {0} Name= {1} Balance= {2}", c.ID, c.Name, c.Balance);
        }
        public class Customer
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public double Balance { get; set; }
        }
    }
}
 النتيجة:



استخدام foreach لطباعة جميع الـItems  List

مثال,
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 1, Name = "Slah", Balance = 5200 };
            Customer customer2 = new Customer() { ID = 2, Name = "Nasr", Balance = 3500 };
            Customer customer3 = new Customer() { ID = 3, Name = "Mona", Balance = 1700 };

            List<Customer> customerList = new List<Customer>(2);
            customerList.Add(customer1);
            customerList.Add(customer2);
            customerList.Add(customer3);

            foreach (Customer item in customerList)
            {
                Console.WriteLine("Id = {0} Name= {1} Balance= {2}", item.ID, item.Name, item.Balance);   
            }
           
        }
        public class Customer
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public double Balance { get; set; }
        }
    }
}
النتيجة:




استخدام for لطباعة جميع الـItems  List

مثال,
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 1, Name = "Slah", Balance = 5200 };
            Customer customer2 = new Customer() { ID = 2, Name = "Nasr", Balance = 3500 };
            Customer customer3 = new Customer() { ID = 3, Name = "Mona", Balance = 1700 };

            List<Customer> custLst = new List<Customer>(2);
            custLst.Add(customer1);
            custLst.Add(customer2);
            custLst.Add(customer3);

            for (int i = 0; i < custLst.Count; i ++ )
            {
                Customer c = custLst[i];
                Console.WriteLine("Id = {0} Name= {1} Balance= {2}", c.ID, c.Name, c.Balance);
            }
        }
        public class Customer
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public double Balance { get; set; }
        }
    }
}
النتيجة:





Strongly Type

ما معنى Strongly Type نوع قوي  لناخذ مثال,
List<Customer> custLst = new List<Customer>(2);
custLst.Add(customer1);
custLst.Add(customer2);
custLst.Add(customer3);

custLst.Add(77);

في هذا المثال احاول إضافة عنصر جديد إلى الـ List وهو الرقم 77 ولكن إذا نظرنا في الصورة التالية نلاحظ أن List<Customer> تأخد النوع Customer ونحن نقوم بإضافة الرقم 77 وهو من النوع int فسوف يحدث خطأ ولن تقبل الـ List بيانات من النوع int. وهذا هو مفهوم الـ Strongly Type.




Error     1          The best overloaded method match for 'System.Collections.Generic.List<ConsoleApplication.Program.Customer>.Add(ConsoleApplication.Program.Customer)'
Error     2          Argument 1: cannot convert from 'int' to 'ConsoleApplication.Program.Customer'


استخدام Insert Method

تسخدم Insert Method لإضافة عنصر بموقع معين نقوم نحن بتحديدة مثلا نريد إضافة عنصر جديد ويكون هو أول عنصر داخل الـ List مع وجود عناصر سابقة داخل الـ List.

مثال,
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 1, Name = "Slah", Balance = 5200 };
            Customer customer2 = new Customer() { ID = 2, Name = "Nasr", Balance = 3500 };
            Customer customer3 = new Customer() { ID = 3, Name = "Mona", Balance = 1700 };

            List<Customer> custLst = new List<Customer>(2);
            custLst.Add(customer1);
            custLst.Add(customer2);
            custLst.Add(customer3);

            custLst.Insert(0, customer3);
            foreach (Customer c in custLst)
            {
                Console.WriteLine(c.ID + " " + c.Name + " " + c.Balance );
            }
        }
        public class Customer
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public double Balance { get; set; }
        }
    }
}
النتيجة:



في هذا السطر
custLst.Insert(0, customer3);


قمنا بإضافة العنصر customer3 في الموقع 0  اي في اول القائمة فانلاحظ وجودة مرتين في الأول و الاخر.




استخدام IndexOf

تستخدم IndexOf Method لمعرفة رقم الفرس index الخاص بعنصر محدد.

مثال,

        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 1, Name = "Slah", Balance = 5200 };
            Customer customer2 = new Customer() { ID = 2, Name = "Nasr", Balance = 3500 };
            Customer customer3 = new Customer() { ID = 3, Name = "Mona", Balance = 1700 };

            List<Customer> custLst = new List<Customer>(2);
            custLst.Add(customer1);
            custLst.Add(customer2);
            custLst.Add(customer3);

            int i = custLst.IndexOf(customer2);
            Console.WriteLine(i);
        }
النتيجة:





استخدام Contains Method

تستخدام Contains Method لحديد ما إذا كان عنصر معين موجود داخل الـ List ام لا. تقوم بإرجاع النوع bool. إذا رجع بالقيمة true تم العثور علي العنصر داخل الـ List Collection والعكس صحيح.

مثال,

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

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 1, Name = "Slah", Balance = 5200 };
            Customer customer2 = new Customer() { ID = 2, Name = "Nasr", Balance = 3500 };
            Customer customer3 = new Customer() { ID = 3, Name = "Mona", Balance = 1700 };

            List<Customer> custLst = new List<Customer>(2);
            custLst.Add(customer1);
            custLst.Add(customer2);
            //custLst.Add(customer3);

            if (custLst.Contains(customer3))
                Console.WriteLine("Exist");
            else
                Console.WriteLine("Not Exist");
        }
        public class Customer
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public double Balance { get; set; }
        }
    }
}

النتيجة:


استخدام Exists Method

مثال,

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

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 1, Name = "Slah", Balance = 5200 };
            Customer customer2 = new Customer() { ID = 2, Name = "Nasr", Balance = 3500 };
            Customer customer3 = new Customer() { ID = 3, Name = "Mona", Balance = 1700 };

            List<Customer> custLst = new List<Customer>(2);
            custLst.Add(customer1);
            custLst.Add(customer2);
            custLst.Add(customer3);

            if (custLst.Exists(cust => cust.Name.StartsWith("M") ))
                Console.WriteLine("Exist");
            else
                Console.WriteLine("Not Exist");
        }
        public class Customer
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public double Balance { get; set; }
        }
    }
}

استخدام Find Method

تستخدم للبحث عن عنصر أو قيمة داخال الـ List وغاليا ما نستخدم Lambda Expression


مثال,

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

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 1, Name = "Masrour", Balance = 5200 };
            Customer customer2 = new Customer() { ID = 2, Name = "Abd Allah", Balance = 3500 };
            Customer customer3 = new Customer() { ID = 3, Name = "Aseel", Balance = 1700 };

            List<Customer> custLst = new List<Customer>(2);
            custLst.Add(customer1);
            custLst.Add(customer2);
            custLst.Add(customer3);

            Customer c = custLst.Find(cust => cust.Balance > 2000);
            Console.WriteLine("ID= {0} Name= {1} Balance= {2}", c.ID, c.Name, c.Balance);
        }
        public class Customer
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public double Balance { get; set; }
        }
    }
}


استخدام FindLast Method

تسخدم للبحث عن عنصر يطابق الشرط باستخدام التعبيرات Lambda Expression وإرجاع آخر عنصر مطابق من الـ List.

مثال,

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

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 1, Name = "Masrour", Balance = 5200 };
            Customer customer2 = new Customer() { ID = 2, Name = "Abd Allah", Balance = 3500 };
            Customer customer3 = new Customer() { ID = 3, Name = "Aseel", Balance = 1700 };

            List<Customer> custLst = new List<Customer>(2);
            custLst.Add(customer1);
            custLst.Add(customer2);
            custLst.Add(customer3);

            Customer c = custLst.FindLast(cust => cust.Balance > 2000);
            Console.WriteLine("ID= {0} Name= {1} Balance= {2}", c.ID, c.Name, c.Balance);
        }
        public class Customer
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public double Balance { get; set; }
        }
    }
}

النتيجة:



استخدام FindAll Method

تسخدم للبحث عن عنصر يطابق الشرط باستخدام التعبيرات Lambda Expression وإرجاع كل العنصر المطابقة من الـ List.

مثال,


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

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 1, Name = "Masrour", Balance = 5200 };
            Customer customer2 = new Customer() { ID = 2, Name = "Abd Allah", Balance = 3500 };
            Customer customer3 = new Customer() { ID = 3, Name = "Aseel", Balance = 1700 };

            List<Customer> custLst = new List<Customer>(2);
            custLst.Add(customer1);
            custLst.Add(customer2);
            custLst.Add(customer3);

            List<Customer> customers = custLst.FindAll(cust => cust.Balance > 2000);

            foreach (Customer c in customers)
            {
                Console.WriteLine("ID= {0} Name= {1} Balance= {2}", c.ID, c.Name, c.Balance);
            }
        }
        public class Customer
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public double Balance { get; set; }
        }
    }

}



استخدام FindIndex

تسخدم لمعرفة رقم الـ Index للعنصر المحدد باستخدام التعبيرات Lambda Expression.

مثال,

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

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 1, Name = "Masrour", Balance = 5200 };
            Customer customer2 = new Customer() { ID = 2, Name = "Abd Allah", Balance = 3500 };
            Customer customer3 = new Customer() { ID = 3, Name = "Aseel", Balance = 1700 };

            List<Customer> custLst = new List<Customer>(2);
            custLst.Add(customer1);
            custLst.Add(customer2);
            custLst.Add(customer3);

            int index = custLst.FindIndex(cut => cut.Balance  < 3500);
            Console.WriteLine("Index= {0}", index);
        }
        public class Customer
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public double Balance { get; set; }
        }
    }
}

النتيجة:





التحويل من Array  إلى List باستخدام ToList() Method

مثال,

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

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee employee1 = new Employee() { ID = 1, Name = "Nader", Balance = 5200 };
            Employee employee2 = new Employee() { ID = 2, Name = "Khaled", Balance = 3500 };
            Employee employee3 = new Employee() { ID = 3, Name = "Saoudy", Balance = 1700 };

            Employee[] employeesArray = new Employee[3];
            employeesArray[0] = employee1;
            employeesArray[1] = employee2;
            employeesArray[2] = employee3;

            //Convert From Arrat To List
            List<Employee> employeeList = employeesArray.ToList();

            foreach (Employee item in employeeList)
            {
                Console.WriteLine("ID= {0} Name= {1} Balance = {2}", item.ID, item.Name, item.Balance);
            }
        }
        public class Employee
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public double Balance { get; set; }
        }
    }
}

النتيجة:




التحويل من List إلى Array باستخدام ToArray() Method

مثال,

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

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee employee1 = new Employee() { ID = 1, Name = "Nader", Balance = 5200 };
            Employee employee2 = new Employee() { ID = 2, Name = "Khaled", Balance = 3500 };
            Employee employee3 = new Employee() { ID = 3, Name = "Saoudy", Balance = 1700 };

            List<Employee> empList = new List<Employee>();
            empList.Add(employee1);
            empList.Add(employee2);
            empList.Add(employee3);

            //Convert From List To Array
            Employee[] employees = empList.ToArray();

            foreach (Employee item in employees)
            {
                Console.WriteLine("ID= {0} Name= {1} Balance = {2}", item.ID, item.Name, item.Balance);
            }
        }
        public class Employee
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public double Balance { get; set; }
        }
    }
}

النتيجة هي نفس نتيجة المثال السابق.



التحويل من List إلىDictionary باستخدام ToDictionaryList() Method


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

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee employee1 = new Employee() { ID = 1, Name = "Nader", Balance = 5200 };
            Employee employee2 = new Employee() { ID = 2, Name = "Khaled", Balance = 3500 };
            Employee employee3 = new Employee() { ID = 3, Name = "Saoudy", Balance = 1700 };

            List<Employee> empList = new List<Employee>();
            empList.Add(employee1);
            empList.Add(employee2);
            empList.Add(employee3);

            //Convert From List To Dictionary
            Dictionary<int, Employee> dicEmp = empList.ToDictionary(x => x.ID);

            foreach (KeyValuePair<int,Employee> item in dicEmp)
            {
                Employee em = item.Value;
                Console.WriteLine("ID= {0} Name= {1} Balance = {2}", em.ID, em.Name, em.Balance);
            }
        }
        public class Employee
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public double Balance { get; set; }
        }
    }
}


النتيجة:




استخدام Clear Method - Count() Method

من اسمها تستخدم لمسح جميع عناصر الـ List. تم تعريف List من ثلاث عناصر ثم استخدمنا الإجراء Count() Method لمعرفة عدد العناصر الموجود بالفعل داخل الـ List ثم بعد ذلك استخدمنا الإجراء Clear() Method لحذف جميع عناصر الـ List وقمنا بطباعة عدد عناصر الـ List مرة إخر.

مثال,
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> listAnimals = new List<string>();
            listAnimals.Add("Dog");
            listAnimals.Add("Cat");
            listAnimals.Add("Mouse");
            Console.WriteLine("Animal Count = {0}", listAnimals.Count);

            listAnimals.Clear();
            Console.WriteLine("Animal Count = {0}", listAnimals.Count);
        }
    }
}

النتيجة:





ليست هناك تعليقات:

إرسال تعليق

يسعدني إرسال تعليقاتكم وأسئلتكم واقتراحاتكم