【问题标题】:Finding minimum values of (properties of ) collections in C#在 C# 中查找集合(的属性)的最小值
【发布时间】:2011-04-19 02:09:26
【问题描述】:

鉴于以下来自 Microsoft 示例的代码:

public class EngineMeasurementCollection : Collection<EngineMeasurement>
{
    public EngineMeasurementCollection()
    {
        Add(new EngineMeasurement { Speed = 1000, Torque = 100, Power = 20 });
        Add(new EngineMeasurement { Speed = 2000, Torque = 160, Power = 60 });
        Add(new EngineMeasurement { Speed = 3000, Torque = 210, Power = 125 });
        Add(new EngineMeasurement { Speed = 4000, Torque = 220, Power = 160 });
        Add(new EngineMeasurement { Speed = 5000, Torque = 215, Power = 205 });
        Add(new EngineMeasurement { Speed = 6000, Torque = 200, Power = 225 });
        Add(new EngineMeasurement { Speed = 7000, Torque = 170, Power = 200 });
    }
}
public class EngineMeasurement
{
    public int Speed { get; set; }
    public int Torque { get; set; }
    public int Power { get; set; }
}

如何获得速度或扭矩或功率的最小/最大值。我需要这个来在我正在做的图表上设置比例(准确地说是 WPF 工具包图表)。 我想我可以在 EngineMeasurementCollection 中有一个方法,它遍历每个 EngineMeasurement 并查看功率(或速度),但我怀疑有更简单的方法吗? Collection 类确实有某种 Min 方法,但请注意,我不是试图获得集合的最小值(我不确定在这种情况下这意味着什么),而是特定属性的最小值(例如速度)。我确实看到了 Collection.Min 与仿函数的使用。那里有什么可以做的吗?还是与Linq?我对所有方面都感兴趣。 谢谢, 戴夫

奖金问题(也许这对我来说很明显,答案是最小/最大)。有哪些选项可以决定一个值(例如 Speed 是否已经在集合中)。从这个例子中并不清楚,但如果你已经有了给定自变量的一些数据(例如时间),你就不再需要了。那么有没有像 Collection.Contains("指定你感兴趣的属性") 之类的东西?

【问题讨论】:

    标签: c# .net linq collections minimum


    【解决方案1】:
    using System.Linq;
    
    var collection = new EngineMeasurementCollection();
    int maxSpeed = collection.Max(em => em.Speed);
    

    另请参阅:
    LINQ MSDN documentation
    LINQ to Objects 5 Minute Overview

    【讨论】:

      【解决方案2】:

      添加到 gaearon 的答案:

      int minSpeed = collection.Min(em => em.Speed);
      

      会给你最低限度的。但是您可能会自己解决这个问题;)

      您可以查看this link on MSDN's site,其中介绍了使用 linq 查找最大值/最小值。

      【讨论】:

        【解决方案3】:

        要回答有关“包含”类型方法的问题,如果您想要一个布尔值指示其存在,您可以使用 Any 方法,或者您可以使用 FirstOrDefault 查找第一个出现的 EngineMeasurement满足条件。如果存在,它将返回实际对象,否则将返回该对象的默认值(在这种情况下为 null)。

        bool result = collection.Any(m => m.Speed == 2000); // true
        
        // or
        
        var em = collection.FirstOrDefault(m => m.Speed == 2000);
        if (em != null)
            Console.WriteLine("Torque: {0}, Speed: {1}", em.Torque, em.Speed);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-02-24
          • 2016-10-13
          • 2021-03-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多