如何从使用 LINQ to SQL 的 c# 方法返回匿名类型 [英] How to return anonymous type from c# method that uses LINQ to SQL

查看:28
本文介绍了如何从使用 LINQ to SQL 的 c# 方法返回匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
LINQ to SQL:返回匿名类型?

我有一个标准的 LINQ to SQL 查询,它以匿名类型返回数据(包含大约 6 列各种数据类型的数据).

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.

鉴于它是匿名类型(var"),我该怎么做?

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

编辑 - 这是代码:

    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 };
    }

推荐答案

将匿名类型变成类...

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
    }

这篇关于如何从使用 LINQ to SQL 的 c# 方法返回匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆