using System;
using System.Linq;
using System.Web.UI.WebControls;

namespace System.Web.UI.Controls
{
    public static class ListControlExtensions
    {
        /// <summary>
        /// Set the list control text to a specified value.  First search on text; next search on value.
        /// </summary>
        /// <param name="listControl"></param>
        /// <param name="s">Value or Text to set.</param>
        /// <param name="leaveAloneIfNotFound">If true, then the control isn't changed if the desired item is not found.</param>
        /// <returns>The ListControl.</returns>
        public static ListControl SetSelectedTextOrValue(this ListControl listControl, string s, bool leaveAloneIfNotFound = false)
        {
            int newIndex = -1;

            // First search by text, then by value.
            ListItem listItem = listControl.Items.Cast<ListItem>()
                                    .Where((item1, i) =>
                                               {
                                                   newIndex = i;
                                                   return item1.Text.Equals(s, StringComparison.CurrentCultureIgnoreCase);
                                               })
                                    .FirstOrDefault() ??
                                listControl.Items.Cast<ListItem>()
                                    .Where((item1, i) =>
                                               {
                                                   newIndex = i;
                                                   return item1.Value.Equals(s, StringComparison.CurrentCultureIgnoreCase);
                                               })
                                    .FirstOrDefault();

            if (listItem != null)
            {
                listControl.SelectedIndex = newIndex;
            }
            else if (!leaveAloneIfNotFound)
            {
                // Nothing satisfies the criteria.
                listControl.SelectedIndex = -1;
            }

            return listControl;
        }
    }
}