根据属性值比较列表中的对象

时间:2019-02-10 18:54:14

标签: c# list

为了进行XML序列化,我实现了此结构

[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; }
}

在列表NXRoute的每个元素中,我想在列表Path的元素之间进行比较,并且此比较基于整数属性R_Count的值

==>例如,对于在其属性“ R_Count”中具有最小值的路径,我将进行一次计算/对于其他路径,我将进行另一次计算

我如何实现此比较以对路径元素进行一些计算?

计算示例(更多详细信息): 比较之后:

  • 对于属性为R_Count的路径最小的路径,我将其为属性Preferred="YES"
  • 对于其他路径,请放置其属性Preferred="NO"

1 个答案:

答案 0 :(得分:2)

您可以使用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";
    }
}