What is the purpose of the operator = in the use of lists?

9

What is the purpose of the => operator in the use of List<T> lists, I'm starting to use generic lists and I came across this operator, it is only used in this method LISTA.ForEach(i => Console.WriteLine(i)); ?

Below is my example for illustration:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ListaGenericaCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> LISTA = new List<string>();

            string opcao = "1";

            while (opcao.Equals("1")) 
            {
                Console.WriteLine("Digite um nome para inserir na lista: ");
                string nome = Console.ReadLine();

                LISTA.Add(nome);

                Console.WriteLine("Deseja inserir outro nome na lista? 1-SIM | 2-NAO:");
                opcao = Console.ReadLine();
            }

            LISTA.Sort();
            Console.WriteLine("A lista tem " + LISTA.Count + " itens:");
            LISTA.ForEach(i => Console.WriteLine(i));

            Console.ReadKey();
        }
    }
}

I also noticed that the i variable was not specified as a data type for it, is it a generic type?

    
asked by anonymous 20.11.2015 / 01:23

2 answers

10

None. This is used to create a lambda , which is an anonymous function. This can be used in any situation where an anonymous function / method is expected. It is not related to the list.

i => Console.WriteLine(i)

i is the parameter lambda will receive and Console.WriteLine(i) is the body that will be executed. In this specific case, the ForEach() method will call this lambda for each item in the list passing the item to i .

The type of i is inferred by the compiler through the method signature ForEach .

Another way of writing the same:

(i) => { Console.WriteLine(i); }

Old way using delegate :

delegate(string i) { Console.WriteLine(i); };

This is used when we need functions called callback , where you pass a function to execute, instead of passing the execution result.

Question with more information .

Nomenclature .

More information .

Documentation .

In C # 6 this syntax can be used in common methods within a class. But although the syntax is the same, in this case it would not be a lambda . That is, there is a pointer to a function that will be stored in a variable to be called when it needs it. Example:

public void Imprime(object obj) => Console.WriteLine(obj);
    
20.11.2015 / 01:40
7

The name of this operation is delegate , and functions as a call to a predicate.

The code

LISTA.ForEach(i => Console.WriteLine(i));

Equivalent to

foreach (var i in LISTA)
{
    Console.WriteLine(i);
}
    
20.11.2015 / 01:42