tags:

views:

351

answers:

2

I have two C# (3.5) types that are different from each other. 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:

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

Thoughts?

+7  A: 
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();
Chris Shaffer
Chris, thanks for the answer. Just one note:You need an extra set of parenthesis:( myAList...b.OtherStuff }) ).OrderBy(c=>c.ID) or the OrderBy will not apply to the full new list.
MMind
Good point, added.
Chris Shaffer
+1  A: 
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();
Swim