如何合并两个不同对象的列表? [英] How merge two lists of different objects?

查看:147
本文介绍了如何合并两个不同对象的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#和LINQ,如何合并两个不同对象列表,例如Seminar和Conference? 它们具有一些公共的和一些不同的字段/属性,并且不共享唯一的ID.

Using C# with LINQ, how can I merge two lists of different objects, say, Seminar and Conference? They have some common and some different fields/properties and do not share unique id.

class Seminar
{
   int id,
   DateTime joinDate,
   string name
}

class Conference
{
   Guid confNumber,
   DateTime joinDate
   Type type
}

我有一个清单:

List<Seminar>
List<Conference>

我需要将它们合并为超级List:

I need to merge them into a super List:

List<Object>

代码段会很有帮助.

推荐答案

如果这是您对合并"的定义,则下面的代码对我来说很好用

Following code works fine for me, if this is your definition of Merge

一种解决方案

List<A> someAs = new List<A>() { new A(), new A() };
List<B> someBs = new List<B>() { new B(), new B { something = new A() } };

List<Object> allS = (from x in someAs select (Object)x).ToList();
allS.AddRange((from x in someBs select (Object)x).ToList());

其中A和B是一些类,

class A
{
    public string someAnotherThing { get; set; }
}
class B
{
    public A something { get; set; }
}

另一种解决方案

List<A> someAs = new List<A>() { new A(), new A() };
List<B> someBs = new List<B>() { new B(), new B { something = string.Empty } };

List<Object> allS = (from x in someAs select (Object)new { someAnotherThing = x.someAnotherThing, something = string.Empty }).ToList();
allS.AddRange((from x in someBs select (Object)new { someAnotherThing = string.Empty, something = x.something}).ToList());

A和B的类定义为

class A
{
    public string someAnotherThing { get; set; }
}
class B
{
    public string something { get; set; }
}

这篇关于如何合并两个不同对象的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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