简体   繁体   English

我们可以将匿名类型转换为列表吗 <T> 在C#中使用Linq实体?

[英]Can we Convert Anonymous Type to List <T> using Linq to entity in C#?

I have a table with three columns i want to use self join and retrieve the columns with alias name. 我有一个包含三列的表,我想使用自我连接并检索具有别名的列。

Table: Material(ID,Name,MaterialParentID) 表格: 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 
}
foreach(var row in query)
{
    material mat =new material();
    mat.id=row.ID;
    mat.name=row.Name;

    materilaList.add(mat);
}

return materiList;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM