使用linq合并对象 [英] Using linq to combine objects

查看:58
本文介绍了使用linq合并对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现IEnumerable接口的类的2个实例.我想创建一个新对象,并将它们都组合为一个.我知道我可以使用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'.

解决方案

尝试如下操作:

var combined = firstSequence.Concat(secondSequence);

这是使用 Enumerable.Concat 扩展方法. /p>

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'.

解决方案

Try something like this:

var combined = firstSequence.Concat(secondSequence);

This is using the Enumerable.Concat extension method.

这篇关于使用linq合并对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆