• [ASP.NET]用Linq取CheckBoxList選取項目的值


    前言
    有了Linq to Object之後,一切篩選的動作都變得相當平易近人,甚至上了癮,面對不必要的for loop總是會皺起眉頭。

    今天這篇文章,則是針對當需要串起CheckBoxList的選取項目值時,怎麼樣用Linq來取代for loop。

    需求

    1. CheckBoxList中,若Item被選取,則把值用逗號串起來。


    之前沒有Linq的寫法

        /// <summary>
        /// 使用foreach,判斷item是否selected, 將值加入List後,再轉成string array,使用string.join,透過string.join將值串起來
        /// </summary>
        private void ForLoop()
        {
            var values = new List<string>();
            foreach (ListItem item in this.CheckBoxList1.Items)
            {
                if (item.Selected)
                {
                    values.Add(item.Value);
                }
            }
    
            var result = string.Join(",", values.ToArray<string>());
            this.lblResult.Text = result;
        }


    用Linq的寫法

    碰到的問題:

    1. this.CheckBoxList.Items,無法直接使用Where或Select的方法。

    原因:為什麼無法用Where跟Select的方法呢?因為Where跟Select的方法,是屬於System.Linq這個namespace底下的擴充方法,目標為IEnumerable<T>,回傳也是IEnumerable<T>。
    image

    image

    而因為Items的型別是ListItemCollection,來看一下ListItemCollection實作了哪些東西。
    image 

    從上圖可以看到,ListItemCollection實作了IEnumerable,但為什麼沒有Where可以用?因為Where這個擴充方法是IEnumberable<T>才可以用。

    那要怎麼轉成IEnumerable<T>呢?這邊用到的一樣是System.Linq底下的擴充方法Cast<T>。
    image

    可以看到,這個方法會將IEnumerable轉成IEnumerable<T>,轉成IEnumerable<T>之後,就可以使用Where與Select來篩選我們要的資料了。

        /// <summary>
        /// 透過IEnumerable的Cast,轉成IEnumerable的泛型,就可以使用where, select等方法。直接將篩選結果轉成string array,透過string.join將值串起來
        /// </summary>
        private void LinqCast()
        {
            var result = string.Join(",", this.CheckBoxList1.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => x.Value).ToArray<string>());
            this.lblResult.Text = result;
        }

    結果:
    image

    結論

    雖然只是個微不足道的範例跟小技巧,但卻可以透過這個範例來說明Cast<T>的方式,以及為什麼有些情況某些集合無法直接使用Where與Select的方法,為什麼這些extension method都要想辦法回傳IEnumerable<T>。

    一切的根源,最後就會回到Linq的兩個主要介面:IEnumerable<T>與IEnumerator<T>的互動。

  • 相关阅读:
    request
    href="#"
    可展开收起的客服导航。
    JS添加父节点的方法。
    精简漂亮的导航浮动菜单显示特效演示
    竖排导航
    仿新浪微博
    鼠标滑过改变文字
    滚动函数
    一些常用的兼容函数。
  • 原文地址:https://www.cnblogs.com/chengulv/p/2418606.html
Copyright © 2020-2023  润新知