c# - 返回匿名类型的结果?

标签 c# linq linq-to-sql

使用下面的简单示例,使用 Linq to SQL 从多个表返回结果的最佳方式是什么?

假设我有两个表:

Dogs:   Name, Age, BreedId
Breeds: BreedId, BreedName

我想返回所有带有 BreedName 的狗。我应该让所有的狗都使用这样的东西没有问题:

public IQueryable<Dog> GetDogs()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select d;
    return result;
}

但是如果我想要品种的狗并尝试这个我有问题:

public IQueryable<Dog> GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new
                        {
                            Name = d.Name,
                            BreedName = b.BreedName
                        };
    return result;
}

现在我意识到编译器不会让我返回一组匿名类型,因为它期待 Dogs,但是有没有办法在不必创建自定义类型的情况下返回它?或者我是否必须为 DogsWithBreedNames 创建自己的类并在选择中指定该类型?或者还有其他更简单的方法吗?

最佳答案

我倾向于采用这种模式:

public class DogWithBreed
{
    public Dog Dog { get; set; }
    public string BreedName  { get; set; }
}

public IQueryable<DogWithBreed> GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new DogWithBreed()
                        {
                            Dog = d,
                            BreedName = b.BreedName
                        };
    return result;
}

这意味着您有一个额外的类,但它可以快速轻松地编写代码、易于扩展、可重用且类型安全。

关于c# - 返回匿名类型的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/534690/

相关文章:

c# - 将 SQL 查询转换为 LINQ - 不工作

LINQ 版本的 TOP PERCENT

c# - 使用 LINQ to SQL 的奇怪排序规则问题

c# - 如何查找在 Excel 工作表中选择了哪些单元格?

c# - 如何在具有可变字段的 .NET 应用程序中包含 HTML 文档?

c# - 在编码字符串上使用正则表达式

c# - 在 DataContext 上调用 SubmitChanges 不会更新数据库

asp.net - DropDownList selectedvalue 和表

c# - 无法将带有 [] 的索引应用于类型为“System.Collections.Generic.IEnumerable<>”的表达式

c# - 继承相等比较器