linq+lambda+delegate,从list中查找到满足匹配条件的所有数据索引值

linq的扩展方法中有FindIndex,FindLastIndex两个方法可以查找满足条件的首个和最后一个数据的索引值,利用delegate将匹配条件的方法传入FindAllIndex,查找满足匹配条件的所有索引返回

        /// <summary>
        /// 返回list内所有满足where条件的元素的索引
        /// </summary>
        public static List<int> FindAllIndex<T>(this List<T> list, Func<T, bool> where)
        {
            List<int> indexs = new List<int>();
            if (list != null)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (where(list[i]))
                    {
                        indexs.Add(i);
                    }
                }
            }
            return indexs;
        }

测试:

        public void Test()
        {
            List<string> datas = new List<string>();
            datas.Add("格力");
            datas.Add("铁蛋儿");
            datas.Add("english");
            datas.Add("toyota");
            datas.Add("A");
            var indexs = datas.FindAllIndex(e => e.Length > 2);
            foreach (int i in indexs)
            {
                Console.WriteLine("索引:" + i + ";值:" + datas[i]);
            }
        }

 

转载于:https://www.cnblogs.com/cy2011/p/7417583.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值