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
asvalue
实际上是一个 List 的属性。我尝试了各种化身,例如,value.First().Price
但事实证明它value
的计数始终为零(去图)。
Price
当我将它添加到集合中时,我如何提取Item
它以便我可以跟踪最高和最低价格?此示例假定Item
(s) 都是相同的对象但具有不同的价格。
解决方案
您想要的是实际计算HighestPrice
并LowestPrice
获取它们的值,而不是使它们自动实现的属性,而它们背后没有进一步的逻辑。假设您将物品存储在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
语句添加到源代码的顶部,您就可以在列表变量的自动完成中看到所有这些操作。
推荐阅读
- pyspark - 如何使用均值和标准差从 pyspark 中的多个列中删除异常值
- python - Python:从一个数据帧追加到一个新的数据帧
- mongodb - MongoDB 错误:“MongoServerSelectionError”
- java - 在另一个活动 C 中从活动 A 声明的访问列表?
- sql - Oracle - 不使用隔夜程序刷新的物化视图
- python - 在 Python 中使用嵌入属性解析 XML
- flask - 烧瓶迁移“ValueError:约束必须有一个名称”
- python - 有没有一种优雅的方法可以在 python 中同时解包和索引关键字参数?
- java - 测试从 IntelliJ IDE 中按预期运行,但从命令行 TestNG 运行时没有
- azure - 不同位置之间的网络流量定价 - Azure -