使用 linq 组合对象
我有两个实现 IEnumerable 接口的类实例。我想创建一个新对象并将它们合并为一个。我知道我可以使用 for..each
来执行此操作。
有 linq/lambda 表达式的方法可以做到这一点吗?
编辑
public class Messages : IEnumerable, IEnumerable<Message>
{
private List<Message> message = new List<Message>();
//Other methods
}
代码以组合
MessagesCombined messagesCombined = new MessagesCombined();
MessagesFirst messagesFirst = GetMessageFirst();
MessagesSecond messagesSecond = GetMessageSecond();
messagesCombined = (Messages)messagesFirst.Concat(messagesSecond); //Throws runtime exception
//异常是
Unable to cast object of type '<ConcatIterator>d__71`1[Blah.Message]' to type 'Blah.Messages'.
I have 2 instances of a class that implements the IEnumerable
interface. I would like to create a new object and combine both of them into one. I understand I can use the for..each
to do this.
Is there a linq/lambda expression way of doing this?
EDIT
public class Messages : IEnumerable, IEnumerable<Message>
{
private List<Message> message = new List<Message>();
//Other methods
}
Code to combine
MessagesCombined messagesCombined = new MessagesCombined();
MessagesFirst messagesFirst = GetMessageFirst();
MessagesSecond messagesSecond = GetMessageSecond();
messagesCombined = (Messages)messagesFirst.Concat(messagesSecond); //Throws runtime exception
//Exception is
Unable to cast object of type '<ConcatIterator>d__71`1[Blah.Message]' to type 'Blah.Messages'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我对字节数组也有同样的问题。我做了什么来解决我的问题:
如果你有一个列表:
I had the same problem with an array of byte. What I did to solve my issue:
If you got a list:
尝试这样的操作:
这是使用
Enumerable.Concat
扩展方法。Try something like this:
This is using the
Enumerable.Concat
extension method.Enumarable.Concat
方法返回一个IEnumerable
(或者实际上是一个d__71
,如异常消息所示)。您不能将其转换为Messages
类型。您可以执行以下操作:并确保您的
Messages
类型具有采用IEnumerable
的构造函数:The
Enumarable.Concat
method returns anIEnumerable<Message>
(or in fact an<ConcatIterator>d__71<Message>
as the exception message shows). You can not cast that to yourMessages
type. You can do the following:And make sure your
Messages
type has a constructor taking anIEnumerable<Message>
:您将需要使用Concat。
根据您的编辑:
You will want to use Concat.
Per your edit: