Monday, December 3, 2012

Convert Array to List and List to Array in C#.NET


Below method will convert an array into a list type.


private void ArrayToList()
    {
        string[] nameArr = { "a", "b", "c", "d" };

        List<string> lst = nameArr.OfType<string>().ToList();

        foreach (string item in lst)
        {
            Response.Write(item + ", ");
        }
    }

OutPut:
a, b, c, d

Below method will convert list to an array


private void ListToArray()
    {
        List<string> Namelst = new List<string>();
        Namelst.Add("Chamara");
        Namelst.Add("Janaka");
        Namelst.Add("Asanka");
        Namelst.Add("Lahiru");
        Namelst.Add("Upendra");

        string[] arr = Namelst.ToArray();

        foreach (string item in arr)
        {
            Response.Write(item + ", ");
        }
    }

OutPut:
Chamara, Janaka, Asanka, Lahiru, Upendra

No comments:
Write comments
Recommended Posts × +