C# is there a foreach oneliner available?












15















I just want to know if there is a foreach oneliner in C#, like the if oneliner (exp) ? then : else.










share|improve this question

























  • I think my answer goes straight to the point you want!

    – sergiol
    Jul 6 '18 at 23:44











  • I don't know if it's what the OP wanted, but @sergiol had what I wanted. A way to give foreach a set of literals to be used exactly once.

    – gbarry
    Nov 26 '18 at 19:36


















15















I just want to know if there is a foreach oneliner in C#, like the if oneliner (exp) ? then : else.










share|improve this question

























  • I think my answer goes straight to the point you want!

    – sergiol
    Jul 6 '18 at 23:44











  • I don't know if it's what the OP wanted, but @sergiol had what I wanted. A way to give foreach a set of literals to be used exactly once.

    – gbarry
    Nov 26 '18 at 19:36
















15












15








15


4






I just want to know if there is a foreach oneliner in C#, like the if oneliner (exp) ? then : else.










share|improve this question
















I just want to know if there is a foreach oneliner in C#, like the if oneliner (exp) ? then : else.







c# syntax foreach






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 22 '15 at 15:35









Luis Gouveia

1,94841937




1,94841937










asked Jan 25 '11 at 13:08









WowaWowa

1,32811022




1,32811022













  • I think my answer goes straight to the point you want!

    – sergiol
    Jul 6 '18 at 23:44











  • I don't know if it's what the OP wanted, but @sergiol had what I wanted. A way to give foreach a set of literals to be used exactly once.

    – gbarry
    Nov 26 '18 at 19:36





















  • I think my answer goes straight to the point you want!

    – sergiol
    Jul 6 '18 at 23:44











  • I don't know if it's what the OP wanted, but @sergiol had what I wanted. A way to give foreach a set of literals to be used exactly once.

    – gbarry
    Nov 26 '18 at 19:36



















I think my answer goes straight to the point you want!

– sergiol
Jul 6 '18 at 23:44





I think my answer goes straight to the point you want!

– sergiol
Jul 6 '18 at 23:44













I don't know if it's what the OP wanted, but @sergiol had what I wanted. A way to give foreach a set of literals to be used exactly once.

– gbarry
Nov 26 '18 at 19:36







I don't know if it's what the OP wanted, but @sergiol had what I wanted. A way to give foreach a set of literals to be used exactly once.

– gbarry
Nov 26 '18 at 19:36














6 Answers
6






active

oldest

votes


















41














If you're dealing with an array then you can use the built-in static ForEach method:



Array.ForEach(yourArray, x => Console.WriteLine(x));


If you're dealing with a List<T> then you can use the built-in ForEach instance method:



yourList.ForEach(x => Console.WriteLine(x));


There's nothing built-in that'll work against any arbitrary IEnumerable<T> sequence, but it's easy enough to roll your own extension method if you feel that you need it:



yourSequence.ForEach(x => Console.WriteLine(x));

// ...

public static class EnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");

foreach (T item in source)
{
action(item);
}
}
}





share|improve this answer


























  • Odd enough that they don't have this stuff built in. I guess if one would follow the Python pattern, one would use Select to build a new enumeration?

    – Domi
    Oct 29 '16 at 13:21





















5














List.ForEach Method






share|improve this answer































    4














    foreach line-liners could be achieved with LINQ extension methods. For example:



    instead of:



    var result = new List<string>();
    foreach (var item in someCollection)
    {
    result.Add(item.Title);
    }


    you could:



    var result = someCollection.Select(x => x.Title).ToList();





    share|improve this answer































      3














      Imagine you have three variables and you want to set the same property of them all in only one go:



      foreach (var item in new  {labelA, labelB, labelC})
      {
      item.Property= Value;
      }


      It is the equivalent of doing:



      foreach (var item in new List<SomeType>(){labelA, labelB, labelC})
      {
      item.Property= Value;
      }





      share|improve this answer































        2














        Sure, you can use something like List<>.ForEach:



        List<String> s = new List<string>();
        s.Add("This");
        s.Add("Is");
        s.Add("Some");
        s.Add("Data");
        s.ForEach(_string => Console.WriteLine(_string));





        share|improve this answer

































          0














          The primary difference between if and the ?operator is that if is a statement, while ? produces an expression. I.e. you can do this:



          var _ = (exp) ? then : else; // ok


          but not this:



          var _ = if (exp) { then; } else { else; }; // error


          So if you are looking for something like a foreach expression, there is no .NET type that can naturally return except for void, but there are no values of void type, so you can equally just write:



          foreach (var item in collection) process(item);


          In many functional languages, a Unit type is used instead of void which is a type with only one value. You can emulate this in .NET and create your own foreach expression:



          class Unit
          {
          public override bool Equals(object obj)
          {
          return true;
          }

          public override int GetHashCode()
          {
          return 0;
          }
          }

          public static class EnumerableEx
          {
          public static Unit ForEach<TSource>(
          this IEnumerable<TSource> source,
          Action<TSource> action)
          {
          foreach (var item in source)
          {
          action(item);
          }

          return new Unit();
          }
          }


          However there hardly exists any use-case for such expressions.






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4793885%2fc-sharp-is-there-a-foreach-oneliner-available%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            6 Answers
            6






            active

            oldest

            votes








            6 Answers
            6






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            41














            If you're dealing with an array then you can use the built-in static ForEach method:



            Array.ForEach(yourArray, x => Console.WriteLine(x));


            If you're dealing with a List<T> then you can use the built-in ForEach instance method:



            yourList.ForEach(x => Console.WriteLine(x));


            There's nothing built-in that'll work against any arbitrary IEnumerable<T> sequence, but it's easy enough to roll your own extension method if you feel that you need it:



            yourSequence.ForEach(x => Console.WriteLine(x));

            // ...

            public static class EnumerableExtensions
            {
            public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
            {
            if (source == null) throw new ArgumentNullException("source");
            if (action == null) throw new ArgumentNullException("action");

            foreach (T item in source)
            {
            action(item);
            }
            }
            }





            share|improve this answer


























            • Odd enough that they don't have this stuff built in. I guess if one would follow the Python pattern, one would use Select to build a new enumeration?

              – Domi
              Oct 29 '16 at 13:21


















            41














            If you're dealing with an array then you can use the built-in static ForEach method:



            Array.ForEach(yourArray, x => Console.WriteLine(x));


            If you're dealing with a List<T> then you can use the built-in ForEach instance method:



            yourList.ForEach(x => Console.WriteLine(x));


            There's nothing built-in that'll work against any arbitrary IEnumerable<T> sequence, but it's easy enough to roll your own extension method if you feel that you need it:



            yourSequence.ForEach(x => Console.WriteLine(x));

            // ...

            public static class EnumerableExtensions
            {
            public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
            {
            if (source == null) throw new ArgumentNullException("source");
            if (action == null) throw new ArgumentNullException("action");

            foreach (T item in source)
            {
            action(item);
            }
            }
            }





            share|improve this answer


























            • Odd enough that they don't have this stuff built in. I guess if one would follow the Python pattern, one would use Select to build a new enumeration?

              – Domi
              Oct 29 '16 at 13:21
















            41












            41








            41







            If you're dealing with an array then you can use the built-in static ForEach method:



            Array.ForEach(yourArray, x => Console.WriteLine(x));


            If you're dealing with a List<T> then you can use the built-in ForEach instance method:



            yourList.ForEach(x => Console.WriteLine(x));


            There's nothing built-in that'll work against any arbitrary IEnumerable<T> sequence, but it's easy enough to roll your own extension method if you feel that you need it:



            yourSequence.ForEach(x => Console.WriteLine(x));

            // ...

            public static class EnumerableExtensions
            {
            public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
            {
            if (source == null) throw new ArgumentNullException("source");
            if (action == null) throw new ArgumentNullException("action");

            foreach (T item in source)
            {
            action(item);
            }
            }
            }





            share|improve this answer















            If you're dealing with an array then you can use the built-in static ForEach method:



            Array.ForEach(yourArray, x => Console.WriteLine(x));


            If you're dealing with a List<T> then you can use the built-in ForEach instance method:



            yourList.ForEach(x => Console.WriteLine(x));


            There's nothing built-in that'll work against any arbitrary IEnumerable<T> sequence, but it's easy enough to roll your own extension method if you feel that you need it:



            yourSequence.ForEach(x => Console.WriteLine(x));

            // ...

            public static class EnumerableExtensions
            {
            public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
            {
            if (source == null) throw new ArgumentNullException("source");
            if (action == null) throw new ArgumentNullException("action");

            foreach (T item in source)
            {
            action(item);
            }
            }
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 25 '11 at 13:15

























            answered Jan 25 '11 at 13:09









            LukeHLukeH

            206k45309382




            206k45309382













            • Odd enough that they don't have this stuff built in. I guess if one would follow the Python pattern, one would use Select to build a new enumeration?

              – Domi
              Oct 29 '16 at 13:21





















            • Odd enough that they don't have this stuff built in. I guess if one would follow the Python pattern, one would use Select to build a new enumeration?

              – Domi
              Oct 29 '16 at 13:21



















            Odd enough that they don't have this stuff built in. I guess if one would follow the Python pattern, one would use Select to build a new enumeration?

            – Domi
            Oct 29 '16 at 13:21







            Odd enough that they don't have this stuff built in. I guess if one would follow the Python pattern, one would use Select to build a new enumeration?

            – Domi
            Oct 29 '16 at 13:21















            5














            List.ForEach Method






            share|improve this answer




























              5














              List.ForEach Method






              share|improve this answer


























                5












                5








                5







                List.ForEach Method






                share|improve this answer













                List.ForEach Method







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 25 '11 at 13:10









                Denis PalnitskyDenis Palnitsky

                11k124055




                11k124055























                    4














                    foreach line-liners could be achieved with LINQ extension methods. For example:



                    instead of:



                    var result = new List<string>();
                    foreach (var item in someCollection)
                    {
                    result.Add(item.Title);
                    }


                    you could:



                    var result = someCollection.Select(x => x.Title).ToList();





                    share|improve this answer




























                      4














                      foreach line-liners could be achieved with LINQ extension methods. For example:



                      instead of:



                      var result = new List<string>();
                      foreach (var item in someCollection)
                      {
                      result.Add(item.Title);
                      }


                      you could:



                      var result = someCollection.Select(x => x.Title).ToList();





                      share|improve this answer


























                        4












                        4








                        4







                        foreach line-liners could be achieved with LINQ extension methods. For example:



                        instead of:



                        var result = new List<string>();
                        foreach (var item in someCollection)
                        {
                        result.Add(item.Title);
                        }


                        you could:



                        var result = someCollection.Select(x => x.Title).ToList();





                        share|improve this answer













                        foreach line-liners could be achieved with LINQ extension methods. For example:



                        instead of:



                        var result = new List<string>();
                        foreach (var item in someCollection)
                        {
                        result.Add(item.Title);
                        }


                        you could:



                        var result = someCollection.Select(x => x.Title).ToList();






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jan 25 '11 at 13:13









                        Darin DimitrovDarin Dimitrov

                        844k22230142746




                        844k22230142746























                            3














                            Imagine you have three variables and you want to set the same property of them all in only one go:



                            foreach (var item in new  {labelA, labelB, labelC})
                            {
                            item.Property= Value;
                            }


                            It is the equivalent of doing:



                            foreach (var item in new List<SomeType>(){labelA, labelB, labelC})
                            {
                            item.Property= Value;
                            }





                            share|improve this answer




























                              3














                              Imagine you have three variables and you want to set the same property of them all in only one go:



                              foreach (var item in new  {labelA, labelB, labelC})
                              {
                              item.Property= Value;
                              }


                              It is the equivalent of doing:



                              foreach (var item in new List<SomeType>(){labelA, labelB, labelC})
                              {
                              item.Property= Value;
                              }





                              share|improve this answer


























                                3












                                3








                                3







                                Imagine you have three variables and you want to set the same property of them all in only one go:



                                foreach (var item in new  {labelA, labelB, labelC})
                                {
                                item.Property= Value;
                                }


                                It is the equivalent of doing:



                                foreach (var item in new List<SomeType>(){labelA, labelB, labelC})
                                {
                                item.Property= Value;
                                }





                                share|improve this answer













                                Imagine you have three variables and you want to set the same property of them all in only one go:



                                foreach (var item in new  {labelA, labelB, labelC})
                                {
                                item.Property= Value;
                                }


                                It is the equivalent of doing:



                                foreach (var item in new List<SomeType>(){labelA, labelB, labelC})
                                {
                                item.Property= Value;
                                }






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Jun 14 '18 at 11:19









                                sergiolsergiol

                                2,60222662




                                2,60222662























                                    2














                                    Sure, you can use something like List<>.ForEach:



                                    List<String> s = new List<string>();
                                    s.Add("This");
                                    s.Add("Is");
                                    s.Add("Some");
                                    s.Add("Data");
                                    s.ForEach(_string => Console.WriteLine(_string));





                                    share|improve this answer






























                                      2














                                      Sure, you can use something like List<>.ForEach:



                                      List<String> s = new List<string>();
                                      s.Add("This");
                                      s.Add("Is");
                                      s.Add("Some");
                                      s.Add("Data");
                                      s.ForEach(_string => Console.WriteLine(_string));





                                      share|improve this answer




























                                        2












                                        2








                                        2







                                        Sure, you can use something like List<>.ForEach:



                                        List<String> s = new List<string>();
                                        s.Add("This");
                                        s.Add("Is");
                                        s.Add("Some");
                                        s.Add("Data");
                                        s.ForEach(_string => Console.WriteLine(_string));





                                        share|improve this answer















                                        Sure, you can use something like List<>.ForEach:



                                        List<String> s = new List<string>();
                                        s.Add("This");
                                        s.Add("Is");
                                        s.Add("Some");
                                        s.Add("Data");
                                        s.ForEach(_string => Console.WriteLine(_string));






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Nov 27 '18 at 7:23









                                        Lauren Van Sloun

                                        98511018




                                        98511018










                                        answered Jan 25 '11 at 13:13









                                        Moo-JuiceMoo-Juice

                                        32.2k858114




                                        32.2k858114























                                            0














                                            The primary difference between if and the ?operator is that if is a statement, while ? produces an expression. I.e. you can do this:



                                            var _ = (exp) ? then : else; // ok


                                            but not this:



                                            var _ = if (exp) { then; } else { else; }; // error


                                            So if you are looking for something like a foreach expression, there is no .NET type that can naturally return except for void, but there are no values of void type, so you can equally just write:



                                            foreach (var item in collection) process(item);


                                            In many functional languages, a Unit type is used instead of void which is a type with only one value. You can emulate this in .NET and create your own foreach expression:



                                            class Unit
                                            {
                                            public override bool Equals(object obj)
                                            {
                                            return true;
                                            }

                                            public override int GetHashCode()
                                            {
                                            return 0;
                                            }
                                            }

                                            public static class EnumerableEx
                                            {
                                            public static Unit ForEach<TSource>(
                                            this IEnumerable<TSource> source,
                                            Action<TSource> action)
                                            {
                                            foreach (var item in source)
                                            {
                                            action(item);
                                            }

                                            return new Unit();
                                            }
                                            }


                                            However there hardly exists any use-case for such expressions.






                                            share|improve this answer






























                                              0














                                              The primary difference between if and the ?operator is that if is a statement, while ? produces an expression. I.e. you can do this:



                                              var _ = (exp) ? then : else; // ok


                                              but not this:



                                              var _ = if (exp) { then; } else { else; }; // error


                                              So if you are looking for something like a foreach expression, there is no .NET type that can naturally return except for void, but there are no values of void type, so you can equally just write:



                                              foreach (var item in collection) process(item);


                                              In many functional languages, a Unit type is used instead of void which is a type with only one value. You can emulate this in .NET and create your own foreach expression:



                                              class Unit
                                              {
                                              public override bool Equals(object obj)
                                              {
                                              return true;
                                              }

                                              public override int GetHashCode()
                                              {
                                              return 0;
                                              }
                                              }

                                              public static class EnumerableEx
                                              {
                                              public static Unit ForEach<TSource>(
                                              this IEnumerable<TSource> source,
                                              Action<TSource> action)
                                              {
                                              foreach (var item in source)
                                              {
                                              action(item);
                                              }

                                              return new Unit();
                                              }
                                              }


                                              However there hardly exists any use-case for such expressions.






                                              share|improve this answer




























                                                0












                                                0








                                                0







                                                The primary difference between if and the ?operator is that if is a statement, while ? produces an expression. I.e. you can do this:



                                                var _ = (exp) ? then : else; // ok


                                                but not this:



                                                var _ = if (exp) { then; } else { else; }; // error


                                                So if you are looking for something like a foreach expression, there is no .NET type that can naturally return except for void, but there are no values of void type, so you can equally just write:



                                                foreach (var item in collection) process(item);


                                                In many functional languages, a Unit type is used instead of void which is a type with only one value. You can emulate this in .NET and create your own foreach expression:



                                                class Unit
                                                {
                                                public override bool Equals(object obj)
                                                {
                                                return true;
                                                }

                                                public override int GetHashCode()
                                                {
                                                return 0;
                                                }
                                                }

                                                public static class EnumerableEx
                                                {
                                                public static Unit ForEach<TSource>(
                                                this IEnumerable<TSource> source,
                                                Action<TSource> action)
                                                {
                                                foreach (var item in source)
                                                {
                                                action(item);
                                                }

                                                return new Unit();
                                                }
                                                }


                                                However there hardly exists any use-case for such expressions.






                                                share|improve this answer















                                                The primary difference between if and the ?operator is that if is a statement, while ? produces an expression. I.e. you can do this:



                                                var _ = (exp) ? then : else; // ok


                                                but not this:



                                                var _ = if (exp) { then; } else { else; }; // error


                                                So if you are looking for something like a foreach expression, there is no .NET type that can naturally return except for void, but there are no values of void type, so you can equally just write:



                                                foreach (var item in collection) process(item);


                                                In many functional languages, a Unit type is used instead of void which is a type with only one value. You can emulate this in .NET and create your own foreach expression:



                                                class Unit
                                                {
                                                public override bool Equals(object obj)
                                                {
                                                return true;
                                                }

                                                public override int GetHashCode()
                                                {
                                                return 0;
                                                }
                                                }

                                                public static class EnumerableEx
                                                {
                                                public static Unit ForEach<TSource>(
                                                this IEnumerable<TSource> source,
                                                Action<TSource> action)
                                                {
                                                foreach (var item in source)
                                                {
                                                action(item);
                                                }

                                                return new Unit();
                                                }
                                                }


                                                However there hardly exists any use-case for such expressions.







                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Nov 27 '18 at 6:08









                                                Lauren Van Sloun

                                                98511018




                                                98511018










                                                answered Jan 25 '11 at 13:25









                                                Konstantin OznobihinKonstantin Oznobihin

                                                4,4401628




                                                4,4401628






























                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4793885%2fc-sharp-is-there-a-foreach-oneliner-available%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                                                    Calculate evaluation metrics using cross_val_predict sklearn

                                                    Insert data from modal to MySQL (multiple modal on website)