joesan
joesan

Reputation: 15345

LINQ select into object

How can I box the result of a LINQ select into multiple objects? With the following select clause:

  select new {
        Person = new Person((String)al.Element("firstName"), (String)al.Element("lastName")),
        TimePeriod = new TimePeriod((String)al.Element("start"), (String)al.Element("end"))     
    };

In the example snippet above, Person and TimePeriod are totally unreleated object. Coming from a Scala background, I would have been happy if the result would be boxed into a tuple. Since I'm new to C#, can anyone help me with this?

Upvotes: 0

Views: 396

Answers (1)

juharr
juharr

Reputation: 32266

If you want to put them into a Tuple you can do this

select Tuple.Create(new Person(...), new TimePeriod(...));

But it would be more advisable to create your own class

public class PersonAndTime
{
    public PersonAndTime(Person person, TimePeriod timePeriod)
    {
        Person = person;
        TimePeriod = timePeriod;
    } 
    public Person Person{ get; private set; }
    public TimePeriod TimePeriod {get; private set; }
}

And do this

select new PersonAndTime(new Person(...), new TimePeriod(...));

If you don't need to pass the results of the query into or out of a method then leaving it in the anonymous class should be fine.

Upvotes: 5

Related Questions