How to return anonymous type from c# method that uses LINQ to SQL

alchemical picture alchemical · Jul 1, 2009 · Viewed 78.8k times · Source

Possible Duplicate:
LINQ to SQL: Return anonymous type?

I have a standard LINQ to SQL query, which returns the data as an anonymous type (containing about 6 columns of data of various datatypes).

I would like to make this returned object available to other parts of the program, either by returning it to the method-caller, or by assigning it to a property of the object containing the method.

How can I do this given that it is an anonymous type ("var")?

EDIT - Here is the code:

    using (ormDataContext context = new ormDataContext(connStr))
    {
        var electionInfo = from t1 in context.elections
                   join t2 in context.election_status
                   on t1.statusID equals t2.statusID
                   select new { t1, t2 };
    }

Answer

user110714 picture user110714 · Jul 1, 2009

Make the anonymous type into a class...

public class Person
{
    public Person() {
    }

    public String Name { get; set; }
    public DateTime DOB { get; set; }
}


Person p = 
    from person in db.People 
    where person.Id = 1 
    select new Person { 
        Name = person.Name,
        DOB = person.DateOfBirth
    }