AngleSharp by AngleSharp

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

 OptionsCollection

A collection specialized on IHtmlOptionElement elements.
using AngleSharp.Dom.Html; using AngleSharp.Extensions; 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)) { foreach (IHtmlOptionElement option in _options) { if (option.Id.Is(name)) return option; } return _parent.Children[name] as IHtmlOptionElement; } return null; } } 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) { return _options.GetItemByIndex(index); } 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) { if (index >= 0 && index < Length) { IHtmlOptionElement optionAt = GetOptionAt(index); _parent.RemoveChild(optionAt); } } private IEnumerable<IHtmlOptionElement> GetOptions() { foreach (INode childNode in _parent.ChildNodes) { IHtmlOptionsGroupElement htmlOptionsGroupElement = childNode as IHtmlOptionsGroupElement; if (htmlOptionsGroupElement != null) { foreach (INode childNode2 in htmlOptionsGroupElement.ChildNodes) { IHtmlOptionElement htmlOptionElement = childNode2 as IHtmlOptionElement; if (htmlOptionElement != null) yield return htmlOptionElement; } } else if (childNode is IHtmlOptionElement) { yield return (IHtmlOptionElement)childNode; } } } public IEnumerator<IHtmlOptionElement> GetEnumerator() { return _options.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }