[英]Order two different C# lists with LINQ
I have two C# (3.5) types that are different from each other. 我有两种不同的C#(3.5)类型。 I do not control them so I can not make them inherit from a common type or implement an interface.
我不控制它们,所以我不能让它们从常见类型继承或实现接口。 But they are very similar in "shape":
但它们在“形状”上非常相似:
class A
{
string Name
string Data
}
class B
{
string Title
string OtherStuff
}
class C
{
string ID
string ExtendedData
}
List< A > myAList
List< B > myBList
I would like to do the following with a LINQ query: 我想用LINQ查询执行以下操作:
Return all the elements in lists myAList
and myBList
ordered by Name
or Title
(whatever applies) the result must be a List< C >
where ID = Name
or Title
and ExtendedData = Data
or OtherStuff
返回列表中的所有元素
myAList
和myBList
按Name
或Title
排序(无论什么适用),结果必须是List< C >
,其中ID = Name
或Title
, ExtendedData = Data
或OtherStuff
Thoughts? 思考?
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();
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.