C#: Is there a LINQ way to create an array of objects given an array of constructor parameters?

后端 未结 2 438
青春惊慌失措
青春惊慌失措 2020-12-14 01:53

As an example, say I have an array of names and I want to create an array of Person objects by calling a constructor that takes string name.

<
相关标签:
2条回答
  • 2020-12-14 02:23
    // names is string[]
    Person[] people = names.Select(s => new Person(s)).ToArray();
    

    Explanation:

    Enumerable.Select is the LINQ method for projection. That is, taking a sequence of Foos and projecting them to Bars via some rule Func<Foo, Bar> that eats Foos and spits out Bars. Thus

    names.Select(s => new Person(s))
    

    is a projection of the sequence names of type IEnumerable<string> to a sequence of type IEnumerable<Person>. If you know functional programming it plays the role of map.

    Now, there is a subtle point here that is worth understanding; this is almost surely one of the most important yet easily misunderstood aspects of LINQ. This is the concept of deferred execution. When we say

    IEnumerable<Person> persons = names.Select(s => new Person(s));
    

    this does not actually perform the projection (i.e., it does not yet create the instances of Person constructed using the strings in names as constructor parameters). Instead, it creates something that captures the rule of how to project the sequence names into a sequence of Person. It's only when that rule (known as an iterator) is actually executed does the projection take place.

    One way to cause this execution to occur is to use the method Enumerable.ToArray which basically says iterate through the sequence and give me back the results as an array.

    There are other ways to cause the execution to occur. For example

    IEnumerable<Person> persons = names.Select(s => new Person(s)); 
    foreach(Person p in persons) {
        Console.WriteLine(p.Name);
    }
    

    or

    IEnumerable<Person> persons = names.Select(s => new Person(s)); 
    Person p = persons.First();
    

    which would execute the "first" projection (i.e., new Person(names[0])) and assign the result to p.

    Of course, this doesn't even get into exactly what

    s => new Person(s)
    

    is. That's a lambda expression, and you can get an introduction to them in my answer to How does this LINQ Expression work?.

    0 讨论(0)
  • 2020-12-14 02:24

    I'm posting this incase someone else needs a light on a slightly different scenario. This was my case, and I used Jason's answer to get there.

    Imagine you have a class with the person's name, and job title, and you want to fill that object:

    public class Employee
    {
       private string name;
       private string jobTitle;
    
       public Employee(){}
       public Employee(string name, string job)
       {
         this.name = name;
         this.jobTitle = job;
       }
    
      //  getters + setters...
    }
    

    Then you'd do

    var IQueryable<Employee> list = from p in context.Persons 
                                    join j in context.Jobs
                                      on p.jobId == j.jobId
                                    select new Employee(p.Name, j.Title);
    

    Then you'll loop through the list to get the instances

    0 讨论(0)
提交回复
热议问题