AngleSharp by Florian Rappl

<PackageReference Include="AngleSharp" Version="0.8.7.1" />

 OptionsCollection

A collection specialized on IHtmlOptionElement elements.
using AngleSharp.Dom.Html; using System.Collections; using System.Collections.Generic; using System.Linq; namespace AngleSharp.Dom.Collections { internal sealed class OptionsCollection : IHtmlOptionsCollection, IHtmlCollection<IHtmlOptionElement>, IEnumerable<IHtmlOptionElement>, IEnumerable { private readonly IElement _parent; private readonly IEnumerable<IHtmlOptionElement> _options; public IHtmlOptionElement this[int index] { get { return GetOptionAt(index); } } public IHtmlOptionElement this[string name] { get { if (string.IsNullOrEmpty(name)) return null; foreach (IHtmlOptionElement option in _options) { if (option.Id == name) return option; } return _parent.Children[name] as IHtmlOptionElement; } } public int SelectedIndex { get { int num = 0; foreach (IHtmlOptionElement option in _options) { if (option.IsSelected) return num; num++; } return -1; } set { int num = 0; foreach (IHtmlOptionElement option in _options) { option.IsSelected = (num++ == value); } } } public int Length => _options.Count(); public OptionsCollection(IElement parent) { _parent = parent; _options = GetOptions(); } public IHtmlOptionElement GetOptionAt(int index) { if (index < 0) return null; return _options.Skip(index).FirstOrDefault(); } public void SetOptionAt(int index, IHtmlOptionElement value) { IHtmlOptionElement optionAt = GetOptionAt(index); if (optionAt != null) _parent.ReplaceChild(value, optionAt); else _parent.AppendChild(value); } public void Add(IHtmlOptionElement element, IHtmlElement before = null) { _parent.InsertBefore(element, before); } public void Add(IHtmlOptionsGroupElement element, IHtmlElement before = null) { _parent.InsertBefore(element, before); } public void Remove(int index) { IHtmlOptionElement optionAt = GetOptionAt(index); if (optionAt != null) _parent.RemoveChild(optionAt); } private IEnumerable<IHtmlOptionElement> GetOptions() { foreach (INode childNode in _parent.ChildNodes) { IHtmlOptionsGroupElement optgroup = childNode as IHtmlOptionsGroupElement; if (optgroup != null) { foreach (INode childNode2 in optgroup.ChildNodes) { IHtmlOptionElement option = childNode2 as IHtmlOptionElement; if (option != null) yield return option; } } else if (childNode is IHtmlOptionElement) { yield return (IHtmlOptionElement)childNode; } } } public IEnumerator<IHtmlOptionElement> GetEnumerator() { return _options.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }