如何根据列表成员的属性拆分通用列表(T)?
我有一个(Foo 的)通用列表,其中包含 n 个 Foo 类型的对象。 Foo 的属性之一是 PropertyA。 PropertyA 可以是 ValueA、ValueB 或 ValueC 之一。有没有一种简单的方法可以将其分成三个单独的列表,一个用于 ValueA,一个用于 ValueB,一个用于 ValueC?
我可以编写一些代码来循环原始列表并根据属性值将每个项目添加到新列表中,但这似乎不太容易维护(例如,如果我突然得到一个 ValueD 怎么办?)
**编辑。我应该提到我正在使用该框架的 2.0 版本。
I have a generic List (of Foo) which contains n objects of Type Foo. One of the properties of Foo is PropertyA. PropertyA can be one of ValueA, ValueB or ValueC. Is there an easy way of splitting this into three seperate Lists, one for ValueA, one for ValueB and one for ValueC?
I can write some code which loops the original list and adds each item to a new list based on the property value but this does not seem to be very maintainable (what if I suddenly get a ValueD for example?)
**EDIT. I should have mentioned that I'm using version 2.0 of the framework.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在带有 .Net 2.0 的 C# 中,我已经写了(太多次):
如今,我只是写:
或者
In C# with .Net 2.0, I have written (too many times):
Nowadays, I just write:
Or
在 C# 中我会这样写:
In C# I would write:
如果您想要 valueA、valueB 和 valueC 正好 3 个列表(即使其中之一为空):
否则,请按照其他人的建议使用 GroupBy 运算符。
编辑:由于您使用的是 Framework 2.0,我想您将不得不诉诸循环想法。不过,实现 GroupBy 的通用算法应该不会太困难。类似于
then 循环字典的值。
If you want exactly 3 lists for valueA, valueB and valueC (even if one of them is empty):
Otherwise, use the GroupBy operator as suggested by others.
EDIT: Since you are using Framework 2.0, I guess you'll have to resort to your loop idea. A generic algorithm implementing GroupBy shouldn't be too difficult, though. Something along the lines of
Then loop through the values of the dictionary.
您可以使用 Enumerable.GroupBy:
You can use Enumerable.GroupBy:
请参阅下面的 VB.Net 版本的 C# - 请注意,由于 VB.NET 中没有匿名方法,因此还有一个附加类 (FooFinder),因此我需要一些东西来存储匹配状态。
这是一种更“实用”的方法来完成同样的事情,但仍然使用 C# 2.0 语法。请注意,与其他解决方案(循环/字典)的重要区别是在 List 上使用 FindAll 方法,该方法将迭代您的集合并返回委托返回 true 的所有项目。
C#:
VB.NET:
See below the C# for the VB.Net version - note that there's one additional class (FooFinder) since there are no anonymous methods in VB.NET, so I needed something to be able to store the match state.
Here's a more "functional" way to accomplish the same thing, but still using C# 2.0 syntax. Note the important difference from other solutions (looping/dictionaries) is the use of the FindAll method on List, which will iterate over your collection and return all items for which the delegate returns true.
C#:
VB.NET:
或者,如果
IEnumerable
足够好,您可以省略ToList()
调用。如果对于 ValueX 来说,可能不存在 PropertyA 等于 ValueX 的项目,则
First
将引发异常。在这种情况下,最好这样做:这将为您提供一个空列表,而不是抛出异常。
Or you could leave out the
ToList()
calls if anIEnumerable<Foo>
is good enough.If it is possible that for a ValueX there are no items for which PropertyA equals ValueX, then
First
will throw an exception. In that case, it's a good idea to do this:This will give you an empty list instead of throwing an exception.