You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过迭代方式获取Items类中ICollection属性的最大Count值?

问题解答

背景代码

Items类定义

public class Items
{
    public ICollection<ClassName1> Items1 { get; set; }
    public ICollection<ClassName2> Items2 { get; set; }
    public ICollection<ClassName3> Items3 { get; set; }
}

该类包含三个ICollection类型的强类型属性:Items1、Items2、Items3,对应元素类型分别为ClassName1、ClassName2、ClassName3。

实例初始化代码

var items = new Items()
{
    Items1 = GetItems1(),
    Items2 = GetItems2(),
    Items3 = GetItems3()
};

需求

// 获取items中所有属性集合的最大Count值

问题

  1. 有什么好方法可以获取items中属性的最大Count值?
  2. 如何不通过逐个列举属性(如{ items.Items1.Count, items.Items2.Count, items.Items3.Count }.Max()这种写法),而是通过迭代方式调用Max()来实现?

解决方案

问题1的解答

根据场景不同,有几种可行方案:

  • 直接列举法(推荐小数量属性场景):如果属性数量不多,直接把所有属性的Count放到数组里取最大值是最简单高效的写法,代码直观且性能最优:
    var maxCount = new[] { items.Items1?.Count ?? 0, items.Items2?.Count ?? 0, items.Items3?.Count ?? 0 }.Max();
    
    注:加入?.Count ?? 0是为了处理属性为null的情况,避免空引用异常。
  • 迭代法:对应问题2的解决方案,下面详细说明。

问题2的解答

要实现迭代式取Max,有两种常用方式:

方式1:利用反射遍历属性

通过反射获取Items类中所有ICollection类型的属性,再遍历获取每个属性的Count值,最后取最大值:

using System.Reflection;

var maxCount = typeof(Items)
    .GetProperties(BindingFlags.Public | BindingFlags.Instance)
    // 筛选出ICollection或其子类型的属性
    .Where(p => typeof(ICollection).IsAssignableFrom(p.PropertyType))
    // 获取属性值并转成ICollection,处理null情况
    .Select(p => ((ICollection)p.GetValue(items))?.Count ?? 0)
    .Max();

注意:反射存在一定性能开销,高频调用场景不推荐;必须处理属性为null的情况,否则会抛出空引用异常。

方式2:在Items类中封装集合枚举方法(推荐可修改类的场景)

如果有权限修改Items类,可以添加一个方法返回所有ICollection属性的集合,既类型安全又无反射性能问题:

public class Items
{
    public ICollection<ClassName1> Items1 { get; set; }
    public ICollection<ClassName2> Items2 { get; set; }
    public ICollection<ClassName3> Items3 { get; set; }

    // 封装返回所有集合属性的方法
    public IEnumerable<ICollection> GetAllCollections()
    {
        yield return Items1;
        yield return Items2;
        yield return Items3;
    }
}

调用时直接迭代该方法返回的集合即可:

var maxCount = items.GetAllCollections()
    .Select(c => c?.Count ?? 0)
    .Max();

这种方法可读性高、类型安全,性能和直接列举法接近,是长期维护的最优选择。

内容的提问来源于stack exchange,提问作者alrightgame

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 06:00:03