Reputation: 118
I have the following code that does what I want however I was wondering if there was a way to do the same thing directly from a linq query.
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);
}
Thanks in advance,
-EC-
Edit 1.
I managed to get what I wanted with using the suggestion from SLaks... I'll give it another shot at the .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();
Upvotes: 1
Views: 1828
Reputation: 4189
Using dot/fluent syntax, this is what I believe you want:
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()
accomplishes the same thing as grouping but only using the keys. As written, this Distinct()
implementation is nearly identical to what you already had, but it may perform better and/or use less memory.
Upvotes: 0
Reputation: 887459
select new Dictionary<string, string> {
{ "employeeID", ex.Key.title },
...
}
Upvotes: 3