在添加到List <t>时在List <t>的集合上设置属性

时间:2018-11-09 19:26:46

标签: c#

我需要根据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.Price的属性,因为value实际上是一个列表。我已经尝试过各种化身,例如value.First().Price,但事实证明value的总计数为零(按数字)。

在将Price中的Item添加到集合中后,如何跟踪最高和最低价格?此示例假设Item(s)都是同一物品,但价格不同。

1 个答案:

答案 0 :(得分:0)

您想要的是在获取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并只需使用List<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语句添加到源代码顶部后,您可以在列表变量的自动完成功能中看到所有这些操作。