zoukankan      html  css  js  c++  java
  • 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]);
                }
            }

  • 相关阅读:
    轻时代来临 资深架构师分享手游五大设计要点
    Netty 介绍
    Socket编程与线程
    java多线程并发访问解决方案
    throws 和throw 的区别
    JRE
    Servlet的生命周期
    页面介绍
    项目技术介绍
    软件开发环境
  • 原文地址:https://www.cnblogs.com/cy2011/p/7417583.html
Copyright © 2011-2022 走看看