Amibluesky
Amibluesky

Reputation: 189

compare objects inside a list according to their property value

In order to do a XML Serialization, I implemented this structure

[XmlRoot("NXRoutes")]
public class NXRoutes
{
    [XmlElement("NXRoute")]
    public List<NXRoute> NXRoute { get; set; }
}

public class NXRoute
{
    [XmlAttribute("ID")]
    public string ID { get; set; }
    [XmlElement("Path")]
    public List<Path> Path { get; set; }
}

public class Path
{
    [XmlAttribute("Nbr_R")]
    public int R_count { get; set; }
    [XmlAttribute("ID")]
    [XmlAttribute("Preferred")]
    public string Preferred { get; set; }
}

in each element of my list NXRoute i would like to make comparison between the elements of the list Path and this comparison is based on the value of the integer attribute R_Count

==> For example for the path that has the smallest value in its attribute "R_Count" I would do a calculation / and for others I would do another calculation

how can i implement this comparison to do some calculation on the path element ?

example of calculation (for more details): after comparaison :

Upvotes: 0

Views: 54

Answers (1)

Haytam
Haytam

Reputation: 4733

you could do this using LINQ:

// Assuming nxRoutes is your NXRoutes object
foreach (var route in nxRoutes.NXRoute)
{
    var paths = route.Path.OrderBy(p => p.R_count).ToArray();
    // This will return a list of paths ordered by the count
    // This means the first one is the smallest
    paths[0].Preferred = "YES";

    // Set the others to NO
    for (int i = 1; i < paths.Length; i++)
    {
        paths[i].Preferred = "NO";
    }
}

Upvotes: 2

Related Questions