Home > Software engineering >  How to detect and remove duplicates from List in XmlArray (when reading in)
How to detect and remove duplicates from List in XmlArray (when reading in)

Time:03-02

This is one attribute of a larger XML object (expressed in C#):

[XmlArray]
public List<CustomAssignment> CustomAssignments
{
    get => _CustomAssignments; set { _CustomAssignments = value; }
}
private List<CustomAssignment> _CustomAssignments = new List<CustomAssignment>();

The CustomAssignment object is:

public class CustomAssignment
{
    [XmlAttribute]
    public int Index
    {
        get => _Index; set => _Index = value;
    }
    private int _Index;
}

I have noticed that sometimes I have duplicates in the XML data. For example:

<CustomAssignments>
  <CustomAssignment Index="0" />
  <CustomAssignment Index="0" />
</CustomAssignments>

I now know why it has been happening, so I can prevent it in the future. But is there an easy way to delete this duplicates from my List?

Can this be acheived when the XML file is being serialized in?

CodePudding user response:

suppose you have a variable called '_data' that ts filled with your XML data.

you can easily do this:

_data = _data.GroupBy(x => x.Index).Select(x => x.FirstOrDefault()).ToList();
  • Related