views:

233

answers:

1

I want to merge two lists of different types into one list of new type. I would use join, but if for example List A doesnt have a value for that common property, i still want to use the values for List B.

class A{
 decimal AValue
 DateTime Date
 int UserID
 }

class B{
 int BValue
 DateTime Date
 int UserID
 }

class Merge{
 decimal? Avalue
 int? BValue
 DateTime Date
 int UserID

 }
A: 

If I understand correctly, this should do it. As there are 2 dates to choose, I've selected the one from the blist.

Assuming alist as IEnumerable<A> and blist as IEnumerable<B>

EDIT: The previous answer joined the wrong way allowing nulls for the B part of the join. I've updated the code to allow null As instead

blist
    .GroupJoin
    (
        alist,
        tb => tb.UserID,
        ta => ta.UserID,
        (tb, ta) => new {tb, ta}
    )
    .SelectMany
    (
        j => j.ta.DefaultIfEmpty(),
        (j, x) =>
        new Merge
            {
                AValue = x.AValue,
                BValue = j.tb.BValue,
                Date = j.tb.Date,
                UserID = j.tb.UserID
            }
    );
spender
blist is always the same.
zsharp
so are there items in alist that don't have a corresponding item in blist? is this a full outer join rather than just a left outer join?
spender