我有两种不同的C#(3.5)类型。我不控制它们,所以我不能让它们从常见类型继承或实现接口。但它们在“形状”上非常相似:
class A
{
string Name
string Data
}
class B
{
string Title
string OtherStuff
}
class C
{
string ID
string ExtendedData
}
List< A > myAList
List< B > myBList
我想用LINQ查询执行以下操作:
返回myAList
或myBList
排序的列表Name
和Title
中的所有元素(无论适用),结果必须为List< C >
ID = Name
1}}或Title
和ExtendedData = Data
或OtherStuff
思想?
答案 0 :(得分:7)
var myCList = (myAList.Select(a => new C
{ ID = a.Name, ExtendedData = a.Data })
.Union(myBList.Select(b => new C
{ ID = b.Title, ExtendedData = b.OtherStuff }))
.OrderBy(c => c.ID)
.ToList();
答案 1 :(得分:1)
var result = (
from a in myAList
select new C { ID = a.Name, ExtendedData = a.Data }
).Union(
from b in myBList
select new C { ID = b.Title, ExtendedData = b.OtherStuff }
).OrderBy(e => e.ID).ToList();