Linq to object Duplication delete

时间:2016-02-21 13:10:15

标签: c# linq

我有这样的代码;

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");

我想删除一个相同的项目(我只需要一个&#34; RegExRules2&#34;而不是两个)。

但是,失败了。

我该怎么办? (我猜,我不擅长&#34; Distinct()&#34;)

由于

2 个答案:

答案 0 :(得分:2)

您可以执行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");

答案 1 :(得分:1)

另一种可能性是为IEqualityComparer创建XElement

一个非常基本的例子(您不应该将其视为GetHashCodeLook here for that的实施的一个好例子):

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());