0

I have been reading about the LINQ feature of c# and come across the following bit of code:

List<string> myFruitList = new List<string>() {
    "apple", "plum", "cherry", "grape", "banana", "pear", "mango" ,
    "persimmon", "lemon", "lime", "coconut", "pineapple", "orange"};

    var results = from e in myFruitList
                  where e[0] == 'p' || e[0] == 'l'
                  group e by new {
                      FirstChar = e[0],
                      LengthGt5 = e.Length > 5  //no type mentioned for FirstChar and LengthGt5
                  };

What I am unable to understand is no type was mentioned for FirstChar(char) and LengthGt5(bool) fields. I am pretty confused. Please clear the doubts. Thanks in advance.

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
Victor Mukherjee
  • 10,487
  • 16
  • 54
  • 97

4 Answers4

1

It is nothing, but the Type Inference

ie.
  • 5,982
  • 1
  • 29
  • 44
1

The type is inferred from the Linq statement. Since myFruitList is a List<string>, e is by definition a string. The FirstChar type is inferred from the fact that you take a char at index 0 from a string, so that's bound to be a char.

Wim Ombelets
  • 5,097
  • 3
  • 39
  • 55
0

Those are public read-only properties of an anonymous type so as you point out, they take on the type of what is assigned to them.

Justin Harvey
  • 14,446
  • 2
  • 27
  • 30
0

In your snippet, you are using the object initialization technique.

In this case, the compiler is able to identify the type of the object that you are using to implement the group by clause (string). From there, it is able to infer the properties or fields that this object type contains.

With this information, it can provide you a way to do object initialization using anonymous types for the object type public members (properties or fields).

HuorSwords
  • 2,225
  • 1
  • 21
  • 34