Why do you print the variable type instead of the result?

2

See the method below:

public void TesteLambda() {
            List<String> selecoes = new List<string>();
            selecoes.Add("USA");
            selecoes.Add("Brasil");
            selecoes.Add("Itália");
            selecoes.Add("França");

            // Primeira forma de fazer um filtro usando WHERE
            var melhorSelecao =
                from string s in selecoes
                where s == "Brasil"
                select s;

            Console.WriteLine(melhorSelecao);

            // Segunda forma de fazer um filtro usando WHERE
            var melhorSelecao2 = selecoes.Cast<string>().Where(s => s == "Itália");
            var melhorSelecao3 = selecoes.Where(s => s == "França");
        }

As you can see the variables should return one of the values in the list, but what is returning is this:

{System.Linq.Enumerable.WhereListIterator<string>}

What's wrong?

    
asked by anonymous 17.08.2017 / 08:52

3 answers

4

In fact, you are ordering to print a list and this is the result you should get. If you want to print the items in the list then you should use a structure that scrolls through the list and shows your items.

using static System.Console;
using System.Collections.Generic;
using System.Linq;

public class Program {
    public static void Main() {
        var selecoes = new List<string>() { "USA", "Brasil", "Itália", "França" };
        var melhorSelecao = from string s in selecoes
                where s == "Brasil"
                select s;
        foreach (var item in melhorSelecao) {
            WriteLine(item);
        }
    }
}

See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference .

    
17.08.2017 / 09:09
2

From what I saw, you're using Where, which always returns a collection of objects. Since you are returning only one object, do it this way:

public void TesteLambda() {
    List<String> selecoes = new List<string>();
    selecoes.Add("USA");
    selecoes.Add("Brasil");
    selecoes.Add("Itália");
    selecoes.Add("França");

    // Primeira forma de fazer um filtro usando WHERE
    var melhorSelecao = selecoes.FirstOrDefault(a => a == "Brasil")                

    Console.WriteLine(melhorSelecao);
}

There's no need to do it the way it was, unless you need to return a collection. If it is a single value, FirstOrDefault () is best.

    
17.08.2017 / 16:27
0

The problem is that you have defined as List a String being a class and started as new List (); being a type of variable.

List<String> selecoes = new List<String>();

//ou

List<string> selecoes = new List<string>();
    
24.08.2017 / 19:49