【发布时间】:2011-07-20 00:57:23
【问题描述】:
我有几行看起来像这样的代码。
XDocument rssDocDistinct = new XDocument(new XElement("rss",
new XElement("channel",
from node in rssDoc.Element("rss").Element("channel").Descendants("item")
select node)));
谁能帮我弄清楚如何在 rssDoc 中只获取不同的“项目”?我不想要任何重复。
感谢您的帮助。
编辑:
<rss version="2.0">
<channel>
<title></title>
<link></link>
<description></description>
<copyright></copyright>
<ttl></ttl>
<item>
<title></title>
<description></description>
<link></link>
<pubDate></pubDate>
</item>
<item>
<title></title>
<description> </description>
<link></link>
<pubDate></pubDate>
</item>
</channel>
</rss>
rssDocDistinct 应该看起来像这样,没有重复的项目元素(具有相同标题、链接、描述、pubDate 的项目只会出现一次)
<item>
<title></title>
<description></description>
<link></link>
<pubDate></pubDate>
</item>
<item>
<title></title>
<description> </description>
<link></link>
<pubDate></pubDate>
</item>
编辑: 感谢你们帮助我弄清楚如何按照 Polishchuc 的建议制作 IEqualityComparer。
public class ItemComparer : IEqualityComparer<XElement>
{
#region IEqualityComparer<XElement> Members
public bool Equals(XElement x, XElement y)
{
return (string)x.Element("title") == (string)y.Element("title")
&& (string)x.Element("description") == (string)y.Element("description")
&& (string)x.Element("link") == (string)y.Element("link")
&& (string)x.Element("pubDate") == (string)y.Element("pubDate");
}
public int GetHashCode(XElement obj)
{
return ((string)obj.Element("title")).GetHashCode()
+ ((string)obj.Element("description")).GetHashCode()
+ ((string)obj.Element("link")).GetHashCode()
+ ((string)obj.Element("pubDate")).GetHashCode();
}
#endregion
}
【问题讨论】:
-
这取决于您对“distinct”含义的衡量,需要查看示例 xml,假设它表示“至少一个属性值不同于任何其他项”
-
我只想删除所有重复项。
-
没有你发布你的 xml,没有人可以给你一个具体的答案——我们怎么知道你的“项目”有什么属性?
-
我添加了我的xml的结构。