在 C# 中过滤集合 [英] Filtering collections in C#

查看:19
本文介绍了在 C# 中过滤集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种非常快速的方法来过滤 C# 中的集合.我目前正在使用通用 List集合,但如果其他结构表现更好,我也愿意使用它们.

I am looking for a very fast way to filter down a collection in C#. I am currently using generic List<object> collections, but am open to using other structures if they perform better.

目前,我只是在创建一个新的 List并循环遍历原始列表.如果过滤条件匹配,我将副本放入新列表中.

Currently, I am just creating a new List<object> and looping thru the original list. If the filtering criteria matches, I put a copy into the new list.

有没有更好的方法来做到这一点?有没有办法就地过滤,这样就不需要临时列表?

Is there a better way to do this? Is there a way to filter in place so there is no temporary list required?

推荐答案

如果您使用的是 C# 3.0,您可以使用 linq,它更好、更优雅:

If you're using C# 3.0 you can use linq, which is way better and way more elegant:

List<int> myList = GetListOfIntsFromSomewhere();

// This will filter ints that are not > 7 out of the list; Where returns an
// IEnumerable<T>, so call ToList to convert back to a List<T>.
List<int> filteredList = myList.Where(x => x > 7).ToList();

如果找不到.Where,则意味着您需要在文件顶部导入using System.Linq;.

If you can't find the .Where, that means you need to import using System.Linq; at the top of your file.

这篇关于在 C# 中过滤集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆