[英]Linq to object Duplication delete
我有这样的代码;
XElement TEST = XElement.Parse(
@"<SettingsBundle>
<SettingsGroup Id=""QAVerificationSettings"">
<Setting Id=""RegExRules"">True</Setting>
<Setting Id=""RegExRules1""><RegExRule><Description>Foo</Description><IgnoreCase>false</IgnoreCase><RegExSource></RegExSource><RegExTarget>[^\s]+@[^\s]+</RegExTarget><RuleCondition>TargetOnly</RuleCondition></RegExRule></Setting>
<Setting Id=""RegExRules2""><RegExRule><Description>Boo</Description><IgnoreCase>false</IgnoreCase><RegExSource></RegExSource><RegExTarget>\s{2,}</RegExTarget><RuleCondition>TargetOnly</RuleCondition></RegExRule></Setting>
<Setting Id=""RegExRules2""><RegExRule><Description>Boo</Description><IgnoreCase>false</IgnoreCase><RegExSource></RegExSource><RegExTarget>\s{2,}</RegExTarget><RuleCondition>TargetOnly</RuleCondition></RegExRule></Setting>
</SettingsGroup>
</SettingsBundle>");
List<XElement> LIST1 = new List<XElement> { };
foreach( XElement x in TEST.Descendants( "RegExRule"))
LIST1.Add(x);
var LIST2 = LIST1.Distinct();
var NEW = new XDocument(
new XElement("SettingsBundle",
new XElement("SettingsGroup", new XAttribute("Id", "QAVerificationSettings"),
new XElement("Settings", new XAttribute("Id", "RegExRules"), "True"),
LIST2.Select((x, i) => new XElement("Setting", new XAttribute("Id", "RegExRules" + i ), x ))
)));
NEW.Save(Directory.GetCurrentDirectory() + @"\_Texting.xml");
我想删除同一项目之一(我只需要一个“ RegExRules2”,而不是两个)。
但是,都失败了。
我需要做什么 ? (我想我不擅长使用“ Distinct()”)
谢谢
您可以执行GroupBy
并仅使用每个组中的第一项来获取不同的元素:
XNamespace ns = "http://schemas.datacontract.org/2004/07/Sdl.Verification.QAChecker.RegEx";
var distinctRules = TEST.Descendants(ns + "RegExRule")
.GroupBy(o => o.ToString())
.Select(o => o.First());
var result = new XDocument(
new XElement("SettingsBundle",
new XElement("SettingsGroup", new XAttribute("Id", "QAVerificationsettings"),
new XElement("Settings", new XAttribute("Id", "RegExRules"), "True"),
distinctRules.Select((x, i) => new XElement("Setting", new XAttribute("Id", "RegExRules" + i), x))
)));
result.Save(Directory.GetCurrentDirectory() + @"\_Texting.xml");
另一种可能性是为XElement
创建IEqualityComparer
。
一个非常基本的示例(您不应将其视为实现GetHashCode
的好示例。请在此处查找 )是:
public class XElementComparer : IEqualityComparer<XElement>
{
public bool Equals(XElement x, XElement y)
{
return x.Parent.Attribute("Id").Value == y.Parent.Attribute("Id").Value;
}
public int GetHashCode(XElement obj)
{
string val = obj.Parent.Attribute("Id").Value;
return val.GetHashCode();
}
}
然后在您的Distinct
操作中将如下所示: var LIST2 = LIST1.Distinct(new XElementComparer());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.