加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

过滤器列表<>对象,而不使用C#2.0中的foreach循环

发布时间:2020-12-15 06:18:50 所属栏目:百科 来源:网络整理
导读:我们如何在List中过滤对象在C#中? 解决方法 假设我们有一个列表 string并且您只想要字符串的长度大于5的项目. 下面的代码将返回一个列表 string结果: Liststring myList = new Liststring();myList.Add("hello");myList.Add("world!");myList.Add("one");m
我们如何在List>中过滤对象在C#中?

解决方法

假设我们有一个列表< string>并且您只想要字符串的长度大于5的项目.

下面的代码将返回一个列表< string>结果:

List<string> myList = new List<string>();
myList.Add("hello");
myList.Add("world!");
myList.Add("one");
myList.Add("large!!");
List<string> resultList = myList.FindAll(delegate(string s) { return s.Length > 5; });

resultList将包含’world!’和“大!!”.
此示例使用anonymous method.它也可以写为:

List<string> myList = new List<string>();
// ..
List<string> resultList = myList.FindAll(OnlyLargerThanFive);

//..

private static bool OnlyLargerThanFive(string s)
{
  return s.Length > 5;
}

上述代表OnlyLargerThanFive也被称为Predicate.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读