1

I am using using the following code and I want to add a string to the output, but i get this error

operator '+' cannot be applied to operands of type 'method group' and 'string'.

     class Program
{
   static void Main(string[] args)
        {
            string sample = "1a2b3c4d";
            MatchCollection matches = Regex.Matches(sample, @"\d");

            List<myclass> matchesList = new List<myclass>();

            foreach (Match match in matches)
            {
                myclass class1 = new myclass();

                class1.variableX.Add(match.Value);

                matchesList.Add(class1);
            }

        foreach (myclass class2 in matchesList)
            class2.variableX.ForEach(Console.WriteLine + " "); // <---- ERROR


        }


}

here is the class

public class myclass
    {
         public List<string> variableX = new List<string>();
    }
abdo refky
  • 145
  • 1
  • 11

1 Answers1

2

If you want to modify string before you use WriteLine method you have two possibilities:

  • class2.variableX.ForEach(s => Console.WriteLine(s + " "));

or

  • class2.variableX.Select(s => s + " ").ForEach(Console.WriteLine);
Rudis
  • 1,177
  • 15
  • 30
  • it's working Great . but in my big code it was only working when i made it like this :: ( " " + s ) . the ( s + " ") other one was displaying what is inside the " " only – abdo refky Mar 06 '16 at 11:55
  • what could be the reason for that . – abdo refky Mar 06 '16 at 12:01
  • i also dont understand what .Select do . thank you very much – abdo refky Mar 06 '16 at 12:01
  • `Select` projects each element of a sequence into a new form [MSDN](https://msdn.microsoft.com/library/bb548891(v=vs.100).aspx).Or some [examples](http://www.dotnetperls.com/linq) of Linq functions. – Rudis Mar 06 '16 at 13:45
  • so why it worked only on invers > ( " " + s ) instead of ( s + " ") – abdo refky Mar 06 '16 at 14:38
  • Can you send part of your big code where it doesn't work. What type is `s` in your code? Has it defined `ToString` method to return any value? – Rudis Mar 06 '16 at 21:35