How to get the index of an item in a list in a single step?

后端 未结 8 1024
旧巷少年郎
旧巷少年郎 2020-11-27 11:16

How can I find the index of an item in a list without looping through it?

Currently this doesn\'t look very nice - searching through the list for the same item twice

相关标签:
8条回答
  • 2020-11-27 12:04

    Here's a copy/paste-able extension method for IEnumerable

    public static class EnumerableExtensions
    {
        /// <summary>
        /// Searches for an element that matches the conditions defined by the specified predicate,
        /// and returns the zero-based index of the first occurrence within the entire <see cref="IEnumerable{T}"/>.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">The list.</param>
        /// <param name="predicate">The predicate.</param>
        /// <returns>
        /// The zero-based index of the first occurrence of an element that matches the conditions defined by <paramref name="predicate"/>, if found; otherwise it'll throw.
        /// </returns>
        public static int FindIndex<T>(this IEnumerable<T> list, Func<T, bool> predicate)
        {
            var idx = list.Select((value, index) => new {value, index}).Where(x => predicate(x.value)).Select(x => x.index).First();
            return idx;
        }
    }
    

    Enjoy.

    0 讨论(0)
  • 2020-11-27 12:04

    That's all fine and good -- but what if you want to select an existing element as the default? In my issue there is no "--select a value--" option.

    Here's my code -- you could make it into a one liner if you didn't want to check for no results I suppose...

    private void LoadCombo(ComboBox cb, string itemType, string defVal = "")
    {
        cb.DisplayMember = "Name";
        cb.ValueMember = "ItemCode";
        cb.DataSource = db.Items.Where(q => q.ItemTypeId == itemType).ToList();
    
        if (!string.IsNullOrEmpty(defVal))
        {
            var i = ((List<GCC_Pricing.Models.Item>)cb.DataSource).FindIndex(q => q.ItemCode == defVal);
            if (i>=0) cb.SelectedIndex = i;
        }
    }
    
    0 讨论(0)
提交回复
热议问题