Using linq to combine objects

橙三吉。 提交于 2019-12-10 18:06:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!