我有
下的实体public class A
{
public string TestMethodName { get; set; }
public string FailedFor { get; set; }
}
public class B
{
public string TestMethodName { get; set; }
public string FailedFor { get; set; }
}
我使用的是Windows窗体。如果我尝试在
下执行联盟private void button2_Click(object sender, EventArgs e)
{
List<A> aCollection = new List<A>();
List<B> bCollection = new List<B>();
aCollection.Add(new A { TestMethodName = "Method1", FailedFor = "DPLServerURL" });
aCollection.Add(new A { TestMethodName = "Method2", FailedFor = "DPLServerURL" });
aCollection.Add(new A { TestMethodName = "Method3", FailedFor = "DPLServerURL" });
aCollection.Add(new A { TestMethodName = "Method4", FailedFor = "DPLServerURL" });
bCollection.Add(new B { TestMethodName = "Method1", FailedFor = "OrderXmlLocation" });
bCollection.Add(new B { TestMethodName = "Method2", FailedFor = "OrderXmlLocation" });
bCollection.Add(new B { TestMethodName = "Method5", FailedFor = "OrderXmlLocation" });
var xx = bCollection.Union(aCollection).ToList();
}
我收到错误的是udner
Error 1 Instance argument: cannot convert from 'System.Collections.Generic.List<WindowsFormsApplication1.B>' to 'System.Linq.IQueryable<WindowsFormsApplication1.A>'
如何联合/合并这些实体?
由于
答案 0 :(得分:2)
替换
bCollection.Union(aCollection)
与
bCollection.Union<object>(aCollection)
这将为其中的两个来源中的每个项目创建一个IEnumerable<object>
。你不能做更聪明的事情,因为尽管有相同的属性,你的班级A
和B
之间也没有任何联系。
答案 1 :(得分:1)
你可以试试这个:
private void button2_Click(object sender, EventArgs e)
{
List<I> aCollection = new List<I>();
List<I> bCollection = new List<I>();
aCollection.Add(new A { TestMethodName = "Method1", FailedFor = "DPLServerURL" });
aCollection.Add(new A { TestMethodName = "Method2", FailedFor = "DPLServerURL" });
aCollection.Add(new A { TestMethodName = "Method3", FailedFor = "DPLServerURL" });
aCollection.Add(new A { TestMethodName = "Method4", FailedFor = "DPLServerURL" });
bCollection.Add(new B { TestMethodName = "Method1", FailedFor = "OrderXmlLocation" });
bCollection.Add(new B { TestMethodName = "Method2", FailedFor = "OrderXmlLocation" });
bCollection.Add(new B { TestMethodName = "Method5", FailedFor = "OrderXmlLocation" });
var xx = bCollection.Union(aCollection).ToList();
}
public class A : I
{
public string TestMethodName { get; set; }
public string FailedFor { get; set; }
}
public class B : I
{
public string TestMethodName { get; set; }
public string FailedFor { get; set; }
}
public interface I
{
string TestMethodName { get; set; }
string FailedFor { get; set; }
}
答案 2 :(得分:1)
在其他答案中提到,由于A
和B
是不同的类型,您不能直接创建两种类型的集合,尽管类具有相同的类别属性。您有几种选择:
A
和B
A
和B
之间创建当前基本类型的集合(object
)选项1和2为您提供了无需强制转换即可访问集合类型属性的好处,而选项3则要求您将项目转换为另一个类以使其有用。
一个问题是 - 为什么你有两种类似完全相同的东西?