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

How do I take an IEnumerable result and turn it into a List <treenode>

如何在 C#、.NET 4.0 和 MVC

中获取 IEnumerable 结果并将其转换为 List<treenode>

我在两个地方有基本相同的查询 运行ning,只想访问数据库一次。我运行在几十个地方查询了两次

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

第二个略有不同,因为它只有 returns 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);
    }
}

好吧,要让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>