i am trying to get the Distinct
from the XMLDocument and load into the Dropdownlist.
var topicNodes = xdoc.SelectNodes("//content:Topic", nsmgr).Cast<XmlNode>().Select(c => c.InnerText).Distinct();
here is my full code:
XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing
xdoc.Load(url);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable);
nsmgr.AddNamespace("content", "sitename.xsd");
var topicNodes = xdoc.SelectNodes("//content:Topic", nsmgr).Cast<XmlNode>().Select(c => c.InnerText).Distinct();
foreach (XmlNode node in topicNodes)
{
string topic = node.Attributes["TopicName"].Value;
//dropdownlist.items.add(new listitem(topic);
this.dropdownlist.Items.Add(new ListItem(topic);
}
dropdownlist.databind();
Why don't you use Linq to XML?
Otherwise create a key value array and use the value to distinct on as key.
Edit:
Your distincting on the InnerText is that the correct value? Try to distinct first and then select the innerText.
Try
var topicNodes = xdoc.SelectNodes("//content:Topic", nsmgr).Cast<XmlNode>()**.Distinct()**.Select(c => c.InnerText).ToList();
Edit2:
Use this method:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> knownKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
You have to select on witch field you would like to distinct. The XmlNode with the same ID is not the same object!