Penguen
Penguen

Reputation: 17298

How can i use generic list with foreach?

if i compiled below codes error return foreach loop how can i solve it?

Error:Error 1 foreach statement cannot operate on variables of type 'Sortlist.MyCalısan' because 'Sortlist.MyCalısan' does not contain a public definition for 'GetEnumerator' C:\Users\yusuf.karatoprak\Desktop\ExcelToSql\TestExceltoSql\Sortlist\Program.cs 46 13 Sortlist


        static void EskiMetodlaListele()
        {
            MyCalısan myCalısan = new MyCalısan();
            Calısan calisan = new Calısan();
            calisan.Ad = "ali";
            calisan.SoyAd = "abdullah";
            calisan.ID = 1;

            myCalısan.list.Add(calisan);

            foreach (Calısan item in myCalısan)
            {
                Console.WriteLine(item.Ad.ToString());
            }
        }


    }

   public class Calısan
    {
        public int ID { get; set; }
        public string Ad { get; set; }
        public string SoyAd { get; set; }

    }

   public class MyCalısan
    {
        public List<Calısan> list { get; set; }
        public MyCalısan()
        {
            list = new List();
        }
    }

Upvotes: 2

Views: 766

Answers (5)

Oded
Oded

Reputation: 499372

You need to iterate over the collection you had defined - the list property:

myCalısan.list.Add(calısan);

foreach (Calısan item in myCalısan.list)
{
    Console.WriteLine(item.Ad.ToString());
}

However, if you want to iterate over myCalısan directly, make the MyCalısan class implement IEnumerable<Calısan>.

Upvotes: 0

David A Moss
David A Moss

Reputation: 239

a few issues need to be fixed before it will compile:

   public class MyCalısan{
public List<Calısan> list { get; set; }
public MyCalısan()
{
    list = new List<Calısan>();
}}

  foreach (Calısan item in myCalısan.list)
        {
            Console.WriteLine(item.Ad.ToString());
        }

Upvotes: 0

this. __curious_geek
this. __curious_geek

Reputation: 43217

I recommend MyCalısan to define as Collection.

public class MyCalısan : Collection<Calısan>
{
}

Upvotes: 1

Mathias
Mathias

Reputation: 15391

You should loop on MyCalisan.list; MyCalisan is just your class, and is not enumerable itself.

Upvotes: 0

Pavel Belousov
Pavel Belousov

Reputation: 1858

Only write foreach (Calısan item in myCalısan.list).

Upvotes: 6

Related Questions