问题
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'.
回答1:
Try something like this:
var combined = firstSequence.Concat(secondSequence);
This is using the Enumerable.Concat extension method.
回答2:
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();
回答3:
The Enumarable.Concat
method returns an IEnumerable<Message>
(or in fact an <ConcatIterator>d__71<Message>
as the exception message shows). You can not cast that to your Messages
type. You can do the following:
var m = new Messages(messagesFirst.Concat(messagesSecond));
And make sure your Messages
type has a constructor taking an IEnumerable<Message>
:
public class Messages : IEnumerable, IEnumerable<Message>
{
private List<Message> message;
public Message(IEnumerable<Message> messages)
{
this.message = new List<Message>(messages);
}
//Other methods
}
回答4:
You will want to use Concat.
Pet[] cats = GetCats();
Pet[] dogs = GetDogs();
IEnumerable<Pet> query = cats.Concat(dogs);
Per your edit:
IEnumerable<Message> messagesCombined;
MessagesFirst messagesFirst = GetMessageFirst();
MessagesSecond messagesSecond = GetMessageSecond();
// if this doesn't work, you can cast both MessagesFirst and MessagesSecond to IEnumerable<Message>
messagesCombined = messagesFirst.Concat(messagesSecond);
来源:https://stackoverflow.com/questions/2600977/using-linq-to-combine-objects