How to iterate through System.Generic.List<T>

I'm using C# - VS 2005.

Can anyone plz. help me.




Answer this question

How to iterate through System.Generic.List<T>

  • magicdds

    Hi,

    I've gone through that foreach, but how to declare any Action<T>, can you give me some examples.



  • 8lu8llz

    You can iterate easily with Action<T> delegate

    List<string> list = new List<string>();

    foreach (string item in list)

    {

    Console.WriteLine(item);

    }

    If you need delegate (but this is more code):

    data.ForEach(MyAction);

    ...

    void MyAction(string item)

    {

    Console.WriteLine(item);

    }



  • Venkat Manohar

    Hi!

    Read about foreach keyword



  • Bochica

    Thanks Galich. Your first suggestion helped me out.

    But In your other suggestion:

    data.ForEach(MyAction);

    ...

    void MyAction(string item)

    {

    Console.WriteLine(item);

    }

    "MyAction" method is having one argument parameter, but in this line of code "data.ForEach(MyAction);", you are not passing-on any value, I'm confused, plz. help me with it.



  • jbullard

    In second case, list will iterate itself and call your method passing values to it. It's not often used, more often used foreach() statement. If you want know more - read about delegates in MSDN.

  • How to iterate through System.Generic.List<T>