簡體   English   中英

Linq到對象復制刪除

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM