如何创建List <dictionary <string,string =“”>&gt;来自linq查询的列表</dictionary <string,>

时间:2012-03-13 15:24:36

标签: linq list dictionary

我有以下代码可以做我想要的但是我想知道是否有办法直接从linq查询做同样的事情。

        XElement xmlData = XElement.Parse(items.Xml);
        var itemsNotSynched =
            (from a in xmlData.Descendants(XName.Get("row", "#RowsetSchema"))
             group a by new
             {
                 employeeID = (string)a.Attribute("ows_EmployeeID"),
                 courseID = (string)a.Attribute("ows_CourseID"),
                 title = (string)a.Attribute("ows_LinkTitle")
             } into ex
             select new
             {
                 ex.Key.title,
                 ex.Key.courseID,
                 ex.Key.employeeID
             } into eb
             select eb).ToArray();

        List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
        foreach(var item in itemsNotSynched)
        {
            Dictionary<string, string> itm = new Dictionary<string, string>();
            itm.Add("employeeID", item.employeeID.ToString());
            if(item.courseID != null)
            {
                itm.Add("courseID", item.courseID.ToString());
            }
            itm.Add("title", item.title.ToString());
            list.Add(itm);
        }

提前致谢,

-EC -

编辑1。

我使用SLaks的建议设法得到我想要的东西...我会再给它一个.Distinct()

    XElement xmlData = XElement.Parse(items.Xml);
    List<Dictionary<string,string>> itemsNotSynched =
        (from a in xmlData.Descendants(XName.Get("row", "#RowsetSchema"))
         group a by new
         {
             employeeID = (string)a.Attribute("ows_EmployeeID"),
             courseID = (string)a.Attribute("ows_CourseID"),
             title = (string)a.Attribute("ows_LinkTitle")
         } into g

         select new Dictionary<string, string>
         { 
            {"employeeID", g.Key.employeeID },
            {"courseID", g.Key.courseID },
            {"title", g.Key.title}
         } into f
         select f).ToList();

2 个答案:

答案 0 :(得分:3)

select new Dictionary<string, string> {
    { "employeeID", ex.Key.title }, 
    ...
}

答案 1 :(得分:0)

使用点/流利语法,这是我认为你想要的:

XElement xmlData = XElement.Parse(items.Xml);
List<Dictionary<string,string>> itemsNotSynched =
     xmlData.Descendants(XName.Get("row", "#RowsetSchema"))
     .Select(a => new
     {
         employeeID = (string)a.Attribute("ows_EmployeeID"),
         courseID = (string)a.Attribute("ows_CourseID"),
         title = (string)a.Attribute("ows_LinkTitle")
     })
     .Distinct()
     .Select(a => new Dictionary<string, string>
     { 
        {"employeeID", a.employeeID },
        {"courseID", a.courseID },
        {"title", a.title}
     })
     .ToList();

Distinct()完成与分组相同的操作,但仅使用密钥。如上所述,这个Distinct()实现几乎与您已有的实现相同,但它可能表现更好和/或使用更少的内存。