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'.
I had the same problem with an array of byte. What I did to solve my issue:
col1.Concat(col2).ToArray();
If you got a list:
col1.Concat(col2).ToList();
Try something like this:
var combined = firstSequence.Concat(secondSequence);
This is using the Enumerable.Concat
extension method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With