我们可以将匿名类型转换为列表< T>吗?在C#中使用Linq实体? [英] Can we Convert Anonymous Type to List <T> using Linq to entity in C#?

查看:429
本文介绍了我们可以将匿名类型转换为列表< T>吗?在C#中使用Linq实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含三列的表,我想使用自我联接并检索具有别名的列.

I have a table with three columns i want to use self join and retrieve the columns with alias name.

表格:Material(ID,Name,MaterialParentID)

public List<Material> GetMaterialList()
{
    List<Material> materilaList = new List<Material>();
    var query = (from c1 in db.Materials
                 join c2 in db.Materials on c1.ID equals c2.MaterialParentID
                 select c2);        

    return query.ToList();
}

我想在现有查询中添加以下内容并返回列表

I want to add following to exisiting query and return the List

select new { c2.ID, c2.MaterialParentID, c2.Name, ParentName = c1.Name })

推荐答案

只需使用实际的具体类型,而不使用匿名类型:

Just use the actual concrete type instead of an anonymous one:

select new Material { 
    ID = c2.ID, 
    MaterialParentID = c2.MaterialParentID, 
    Name = c2.Name,
    ParentName = c1.Name 
}

这篇关于我们可以将匿名类型转换为列表&lt; T&gt;吗?在C#中使用Linq实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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