Tân
Tân

Reputation: 1

linq - from in select

I'm making a small example to understand about from in select.

My example:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person(string name, int age)
    {
        this.Name = name;
        this.Age = age;
    }
}
class Program
{
    static void Main()
    {
        var list = new List<Person>();
        list.Add(new Person(name: "Hermione", age: 20));

        var persons = from p in list select new { p.Age, p.Name };            
        foreach (var person in persons)
        {
            Console.WriteLine($"Name: {person.Name}. Age: {person.Age}");
        }

        var _persons = from p in list select new Person(p.Name, p.Age);
        foreach (var person in _persons)
        {
            Console.WriteLine($"Name: {person.Name}. Age: {person.Age}");
        }
    }
}

Both of them have same result:

Name: Hermione. Age: 20

My question: what's the difference betweeen the first and the second? And when to use the first/second?

Upvotes: 4

Views: 12282

Answers (2)

user5775067
user5775067

Reputation:

First of all here is anonymous type var persons = from p in list select new { p.Age, p.Name }; So you can make random names of properties for example

 var persons = from p in list select new { AgesSomeWithDay = p.Age , FullName = p.Name + p.Name };  

BUT var _persons = from p in list select new Person( p.Name, p.Age); is strongly typed you can't make random named properties because here is new Personand Person class contains two properties which you only and can assign to _persons

Upvotes: 4

Roman
Roman

Reputation: 12201

var persons = from p in list select new { p.Age, p.Name }; - creates anonymous type

var _persons = from p in list select new Person(p.Name, p.Age); - creates Person

According to https://msdn.microsoft.com/en-us/library/bb397696.aspx

Anonymous types typically are used in the select clause of a query expression to return a subset of the properties from each object in the source sequence.

Anonymous types contain one or more public read-only properties. No other kinds of class members, such as methods or events, are valid. The expression that is used to initialize a property cannot be null, an anonymous function, or a pointer type.

Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object.

Upvotes: 3

Related Questions