过滤集合C# [英] Filter in collection c#

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

问题描述

我在C#中有一个集合例如:

  Collection< User>列表= null; 

我需要根据总和参数对其进行过滤.因此,假设我要过滤掉用户ID在1到100之间的用户.

请告知我如何在C#中做到这一点

谢谢阿米特(Amit)

解决方案

假设您使用的是.NET 3.5或更高版本,并且不需要将过滤器设置为 ,只需使用LINQ:

  varfilteredUsers = unfilteredUsers.Where(u => u.UserID< 1 || u.UserID> 100).ToList(); 

请注意,这是在过滤ID为1至100的 个用户,而不是按照其他答案过滤 in 个用户.

如果这没有帮助,请澄清问题.(出于兴趣,为什么要使用 Collection< T> 开头?)

如果您真的需要一个 Collection< T> ,则可以轻松创建一个:

  varfilteredUsers = new Collection< User>(unfilteredUsers.Where(u => u.UserID< 1 || u.UserID> 100).ToList()); 

您甚至可以添加自己的 ToCollection 扩展方法来简化此操作.但是 Collection< T> 通常是指更特定的集合类型(例如 ObservableCollection< T> )的基类-直接构造一个是奇怪的.如果您的API是根据 Collection< T> 编写的,则应将其更改为以 IList< T> 编写的方式,从而为您提供更大的灵活性.

I have a collection in c# For ex:

Collection<User> List = null;

I need to filter it based on sum parameters. so lets say i want to filter out users whos userID is between 1 to 100.

Please advice how i can do this in c#

Thanks Amit

解决方案

Assuming you're using .NET 3.5 or higher, and you don't need the filtering to be in place, just use LINQ:

var filteredUsers = unfilteredUsers.Where(u => u.UserID < 1 || u.UserID > 100)
                                   .ToList();

Note that this is filtering out users with IDs between 1 and 100 rather than filtering them in as per other answers.

If this doesn't help, please clarify the question. (Out of interest, why are you using Collection<T> to start with?)

EDIT: If you really need a Collection<T> you can create one easily enough:

var filteredUsers = new Collection<User>
       (unfilteredUsers.Where(u => u.UserID < 1 || u.UserID > 100)
                       .ToList());

You could even add your own ToCollection extension method to make this simpler. But Collection<T> is usually meant to be the base class for more specific collection types (e.g. ObservableCollection<T>) - it's odd to be constructing one directly. If your API is written in terms of Collection<T>, you should potentially change it to be written in terms of IList<T>, giving you more flexibility.

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

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