Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using linq to combine objects

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'.
like image 287
DotnetDude Avatar asked Dec 29 '22 21:12

DotnetDude


2 Answers

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();
like image 120
Fjodr Avatar answered Jan 01 '23 17:01

Fjodr


Try something like this:

var combined = firstSequence.Concat(secondSequence);

This is using the Enumerable.Concat extension method.

like image 38
Andrew Hare Avatar answered Jan 01 '23 17:01

Andrew Hare