Sunday, April 3, 2011

How can i return List from Class

 class Program
    {
        static void Main(string[] args)
        {
            mylist myitems1 = new mylist("Yusuf","Karatoprak");
            SelectedItemsList slist = new SelectedItemsList();
            slist.Items.Add(myitems1);
            foreach( object o in slist.Items)
            Console.Write(o.ToString()+"\n");
            Console.ReadKey();
        }
    }

    public class mylist
    {
        private string Ad;
        private string SoyAd;
        public mylist(string ad, string soyad)
        {
            Ad = ad;
            SoyAd = soyad;
        }

        public override string ToString()
        {
            return "Ad:" + this.Ad;
        }
    }
    public class SelectedItemsList
    {
        public List Items;

        public SelectedItemsList()
        {
            Items = new List();

        }
    }


i want to return an arraylist or list form mylist class but how? return this.Ad, also retun this.SoayAd etch. Please look ToString() procedure: it is return Ad but i want to return Ad also SoyAd together. Not only Ad ,but also Ad,SoyAd in a List.

From stackoverflow
  • Your question is very unclear, but if you mean you want mylist to have a method which returns a list containing Ad and SoyAd, then just do it like this:

    // This could be a property
    public IList<string> GetAds()
    {
        List<string> ret = new List<string>();
        ret.Add(Ad);
        ret.Add(SoyAd);
        return ret;
    }
    

    If you can make do with IEnumerable<string> you could use an iterator block:

    // This could be a property
    public IEnumerable<string> GetAds()
    {
        yield return Ad;
        yield return SoyAd;
    }
    
  • To return an ArrayList or List, just use "public List someFunction()" or "public ArrayList someFunction()". If this is not what you want, please rephrase your question.

  • To return list only of ad or soyad keep it independent lists, filled on adding

0 comments:

Post a Comment