如何获取IEnumerable结果并将其转换为List <treenode> </treenode>

时间:2015-01-30 17:51:27

标签: asp.net-mvc c#-4.0

如何获取IEnumerable结果并将其转换为C#,. NET 4.0和MVC中的List<treenode>

我基本上在两个地方运行相同的查询,只想一次点击数据库。我在几十个地方运行这个查询两次。

 using (SqlConnection cn = new SqlConnection(DBUtils._connStr))

 string sql = @"SELECT L.Name as Name, L.LocationTypeID as LocationTypeID, L.LocationID as LocationID, L.ParentLocationID as ParentLocationID, ISNULL(L.OrderByNumber, -10000) as SectionOrder, L.FromAddress as FromAddress,
         lojL.Name as Section, lojL.LocationID as SectionID,
                    ISNULL(lojL.Name + ' \ ','') + L.Name as NameWithSection
                    FROM hdLocations as L
              LEFT OUTER JOIN hdLocations as lojL ON L.ParentLocationID = lojL.LocationID
            WHERE L.LocationID > 0 AND L.InstanceID=0 And L.ParentLocationID =0";
sql += " ORDER BY  L.OrderByNumber, L.Name";

IEnumerable<TicketLocation> locations = cn.Query<TicketLocation>(sql);

第二个略有不同,因为它只返回4列到List<treenode>

string sql = @"SELECT LocationID AS id, Name AS data, ParentLocationID, LocationTypeID FROM hdLocations WHERE ParentLocationID=0 AND LocationID > 0";
List<TreeNode> locs = cn.Query<TreeNode>(sql).ToList();

我正在尝试限制此调用,它经常出现在我的应用程序中并尝试在登录时执行,而不是每次加载页面。

修改 我想用第一个结果构建第二个......就像

foreach (TicketLocation TL in locations)
{
    if ((TL.ParentLocationID == 0) && (TL.LocationID > 0))
    {
        TreeNode itemTreeNode = new TreeNode()
        {
            id = TL.LocationID,
            data = TL.Name,
        };
        itemTreeNode.id = TL.LocationID;
        itemTreeNode.data = TL.Name;
        itemTreeNode.parentId = TL.ParentLocationID;
        // itemTreeNode.

        locs.Add(itemTreeNode);
    }
}

1 个答案:

答案 0 :(得分:3)

好吧,要将IEnumerable<TicketLocation>变为List<TicketLocation>,您只需要在其上调用.ToList()即可。就TicketLocationTreeNode的映射而言,您发布的代码有什么问题?您可以通过以下方式大大简化代码:

var locs = locations.Where(m => m.ParentLocationID == 0 && m.LocationID > 0)
    .Select(m => new TreeNode
        {
            id = m.LocationID,
            data = m.Name,
            parentId = m.ParentLocationID
        }).ToList();

这会导致locs成为List<TreeNode>