首页 > 解决方案 > 设置列表集合的属性添加到列表时

问题描述

我需要根据 T 的属性在 List 集合上设置公共属性。这就是我的意思:

public class Item
{
    public decimal Price { get; set; }
    public string Description { get; set; }
}
public class ItemCollection
{
    public decimal HighestPrice { get; set; }
    public decimal LowestPrice { get; set; }

    private List<Item> _collection;

    public List<Item> Collection
    {
        get => _collection;
        set
        {
            _collection = value;

            // Setting HighestPrice and LowestPrice
            if (HighestPrice < value.Price)
                HighestPrice = value.Price;

            if (LowestPrice > value.Price)
                LowestPrice = value.Price;
        }
    }
}

我似乎无法提取value.Priceasvalue实际上是一个 List 的属性。我尝试了各种化身,例如,value.First().Price但事实证明它value的计数始终为零(去图)。

Price当我将它添加到集合中时,我如何提取Item它以便我可以跟踪最高和最低价格?此示例假定Item(s) 都是相同的对象但具有不同的价格。

标签: c#

解决方案


您想要的是实际计算HighestPriceLowestPrice获取它们的值,而不是使它们自动实现的属性,而它们背后没有进一步的逻辑。假设您将物品存储在Collection其中(这又可以成为自动属性),它可能看起来像这样(但不应该,请阅读下文):

public class Item
{
    public decimal Price { get; set; }
    public string Description { get; set; }
}

public class ItemCollection
{
    public decimal HighestPrice
    {
        get
        {
            decimal maxPrice = decimal.MinValue;
            foreach (Item item in Collection)
            {
                if (item.Price > maxPrice)
                    maxPrice = item.Price;
            }
            return maxPrice;
        }
    }

    public decimal LowestPrice
    {
        get
        {
            decimal minPrice = decimal.MaxValue;
            foreach (Item item in Collection)
            {
                if (item.Price < minPrice)
                    minPrice = item.Price;
            }
            return minPrice;
        }
    }

    public List<Item> Collection { get; set; }
}

但是,您可以通过使用 Linq 更优雅地解决这个问题,甚至不需要创建一个类ItemCollection而只需使用 aList<Item>代替。例如:

using System.Collections.Generic;
using System.Linq; // Ensure to have this at the top of your source to access Linq methods.

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Item> items = new List<Item>();
            // Fill list here...

            // Use Linq Max and Min functions.
            // You pass the property to calculate the minimum and maximum from 
            // as x => x.Price (where x would represent an Item currently being
            // compared against another by Linq behind the scenes).
            decimal highestPrice = items.Max(x => x.Price);
            decimal lowestPrice = items.Min(x => x.Price);
        }
    }

    public class Item
    {
        public decimal Price { get; set; }
        public string Description { get; set; }
    }
}

然后Linq 所做的是在“幕后”遍历您的列表,比较您在实例之间传递的每个元素的属性(例如Price每个Item实例的),并返回结果。

您可以看到,您唯一需要在这里真正定义的是Item您已经拥有的类。

Linq 有很多这样的操作,您可以在列表(以及其他可枚举的源,如数组)上执行。只要将using System.Linq语句添加到源代码的顶部,您就可以在列表变量的自动完成中看到所有这些操作。


推荐阅读