如何获取集合的空列表?
我有一个匿名类的集合,我想返回它的空列表。
最好使用的可读表达是什么?
我想到了以下内容,但我认为它们的可读性不够:
var result = MyCollection.Take(0).ToList();
var result = MyCollection.Where(p => false).ToList();
注意:我不想清空集合本身。
任何建议!
I have a collection of anonymous class and I want to return an empty list of it.
What is the best readable expression to use?
I though of the following but I don't think they are readably enough:
var result = MyCollection.Take(0).ToList();
var result = MyCollection.Where(p => false).ToList();
Note: I don't want to empty the collection itself.
Any suggestion!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是关于:
这将返回一个 T 类型的空枚举。如果您确实想要一个 List,那么您可以自由地执行此操作:
Whats about:
This returns an empty enumerable which is of type T. If you really want a List so you are free to do this:
实际上,如果您使用通用扩展,您甚至不必使用任何 Linq 来实现此目的,您已经通过 T 公开了匿名类型
Actually, if you use a generic extension you don't even have to use any Linq to achieve this, you already have the anonymous type exposed through T
鉴于您的第一个建议有效并且应该表现良好 - 如果可读性是唯一的问题,为什么不创建一个扩展方法:
现在您可以将示例重构为
Given that your first suggestion works and should perform well - if readability is the only issue, why not create an extension method:
Now you can refactor your example to
出于性能原因,您应该坚持使用您提出的第一个选项。
另一个会在返回空列表之前迭代整个集合。
因为匿名类型无法在源代码中创建列表。然而,有一种方法可以通过反射来创建这样的列表。
For performance reasons, you should stick with the first option you came up with.
The other one would iterate over the entire collection before returning an empty list.
Because the anonymous type there is no way, in source code, to create a list. There is, however, a way to create such list through reflection.