Tuesday, 7 November 2023

Write a Extension Method to give value from list by providing Type in C#

 --Below Provided a example of list of data:

ArrayList arrayList = new ArrayList();

        arrayList.Add(1);

        arrayList.Add("ABC");

        arrayList.Add(10.2);

        arrayList.Add("XYZ");

--Below providing a input as type


--Below is the output



--Below providing the code snippet

// See https://aka.ms/new-console-template for more information

using System.Collections;

using System.Runtime.CompilerServices;


class Program

{

    static void Main(string[] args)

    {

        ArrayList arrayList = new ArrayList();

        arrayList.Add(1);

        arrayList.Add("ABC");

        arrayList.Add(10.2);

        arrayList.Add("XYZ");


        Console.WriteLine("Enter a Type");

        string inputStr = Console.ReadLine();

        string strResult = ExtensionMethod.GetDataAsPerType(arrayList, inputStr);

        Console.WriteLine(strResult);

        Console.ReadLine();


    }

}


public static class ExtensionMethod

{

    public static string GetDataAsPerType(this ArrayList arrayList, string str)

    {

        string outputStr=string.Empty;

        foreach (object obj in arrayList)

        {

            Type tp = obj.GetType();

            if (str == "Int" && tp.Equals(typeof(int)))

            {

                outputStr += obj+";";

            }else if(str == "String" && tp.Equals(typeof(string)))

            {

                outputStr += obj + ";";

            }

            else if ((str == "Float" || str == "Decimal" || str == "Double") && tp.Equals(typeof(double)))

            {

                outputStr += obj + ";";

            }

        }

        return outputStr;

    }

}


No comments:

Post a Comment