如何通过[Where]过滤后返回[List<>]的驱动集合?
在以下集合中:
public class PersonsCollection : List<Person>
通过 Where
扩展过滤后如何返回 PersonsCollection
的实例?
personCollections.Where(p => p.Name == "Jack").ToList();
// will return IEnumerable<Person>, How to return PersonsCollection?
任何想法!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您必须创建一个新的
PersonsCollection
实例,例如假设您有一个合适的构造函数。
一般来说,无论如何扩展内置集合(而不是使用组合)都是一个坏主意 - 您确定首先想要这种设计吗?
You´d have to create a new instance of
PersonsCollection
instead, e.g.assuming you have an appropriate constructor.
Generally it´s a bad idea to extend the built-in collections anyway (rather than using composition) - are you sure you want this design in the first place?
您可以为
IEnumerable
创建扩展方法ToList()
...You could to create an Extension Method
ToList()
for anIEnumerable<Person>
...像这样的事情:
Something like this:
几种可能性:
您的 PersonsCollection 有一个接受
IEnumerable
的构造函数,因此您可以根据查询结果创建一个新的 PersonsCollection。您可以创建一个新的扩展方法 ToPersonsCollection() 来构造 PersonsCollection(可以与上面的组合。)
您可以更改依赖项,以便其他代码不需要 PersonsCollection,而是可以使用
IEnumerable
(这是我推荐的选项。)< /p>A few possibilities:
Your PersonsCollection has a constructor that accepts an
IEnumerable<Person>
, so you create a new PersonsCollection based on the query result.You can create a new extension method ToPersonsCollection() that constructs the PersonsCollection (may be combined with the above.)
You can change your dependencies so that other code doesn't require a PersonsCollection and can instead work with
IEnumerable<Person>
(this is the option that I'd recommend.)您需要在集合中创建正确的构造函数:
然后您可以像这样过滤它:
从您对 CollectionBase 的评论中,我猜您正在重构不使用泛型的旧代码。 Krzysztof Cwalina 发表了一篇关于 如何从非通用集合转换为通用集合。您还可以在博客文章中找到他的评论为什么
List
不推荐在公共 API 中使用 有趣的是:您可以简单地摆脱
PersonsCollection
并使用Collection
之类的东西来代替。You need to create the proper constructor in your collection:
You can then filter it like this:
From your comment about
CollectionBase
I guess that you are refactoring old code not using generics. Krzysztof Cwalina made a blog post about how to transition from non-generic collections to generic collections. You may also find his comment on a blog post whyList<T>
isn't recommended in public API's interesting:You could simply get rid of
PersonsCollection
and use something likeCollection<Person>
instead.