c# - 通过指定属性的唯一性从 List<> 获取对象

标签 c# .net

这里会详细解释: 我有

public class Season
    {
        #region Public Variables

        private int _id;
        private string _seasonName;
        private int _startMonth;

        #endregion

        #region Public Properties 

        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }

        public int StartMonth
        {
            get { return _startMonth; }
            set { _startMonth = value; }
        }

        public string SeasonName
        {
            get { return _seasonName; }
            set { _seasonName = value; }
        }

        #endregion

        #region Public Constructor

        public Season()
        {
            this._initialize();
        }

        public Season(string pSeasonName, int _pStartMonth,int pID)
        {
            this._initialize(pSeasonName, _pStartMonth, pID);
        }

        #endregion

    }

接下来我有如下所示

IList<Season> seaosns = new List<Season>();
seaosns.Add(new Season("Summer", 4, 1));
seaosns.Add(new Season("Winter", 6, 2));
seaosns.Add(new Season("MidSummer", 10, 1));

这里我需要检查 Ilist Items 中的 ID 是否重复。这可以通过使用 For Loop 来完成,但需要知道是否有其他解决方案。

提前致谢。

最佳答案

最合适的方法是将项目(代替或附加)存储在 Dictionary<int,Season> 中。 ,使用唯一属性 ( Id ) 作为字典中的键。然后你有一个 O(1)查找既可以测试存在性,也可以按键获取 ( Id )。但是请注意,字典不是有序的 - 意思是,它不保证遵守插入顺序或键顺序。顺序未定义 - 因此如果您需要它们的特定顺序,您可能需要单独保存。

关于c# - 通过指定属性的唯一性从 List<> 获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10811162/

相关文章:

.net - .NET 中的局部变量命名约定

c# - 在具有不同参数的接口(interface)中定义一个方法(C#)

c# - 如何使我的 Web 项目中的链接图像出现在我的本地开发 Web 服务器上?

c# - 如何从 IPN 加密货币获得响应

c# - 如何将字节 block 读入结构

c# - 添加 OxyPlot PointAnnotation

java - 如何在不测试调用数据库的私有(private)方法的情况下进行单元测试

c# - 如何在运行时创建 WPF UserControl 的图像

c# - 使用 RX 查询,如何在每秒 3 秒的窗口内获取哪些记录具有相同状态?

.net - Silverlight 本地化 - 如何覆盖 Windows 区域性