开发者

LINQ Join and GroupJoin

I have a list of objects, those objects may or may not have contact info:

            // Join contact
        开发者_运维技巧query = query.Join(
        (new ContactRepository(this.Db)).List().Where(x => x.IsMainContact),
        x => new { x.ListItem.ContentObject.LoginId },
        y => new { y.LoginId },
        (x, y) => new ListItemExtended<ListItemFirm>
        {
            City = y.City,
            State = y.State,
            Country = y.Country
        });

This does inner join on 'LoginId'. But I need an outter join so that if contact info does not exists for a given LoginId it will be empty. Please help

thanks


You should execute outer join manually:

            var contacts = (new ContactRepository(this.Db)).List();
            query.Select(item => 
            {
                var foundContact = contacts.FirstOrDefault(contact => contact.Id == item.Id);
                return  new ListItemExtended<ListItemFirm>()
                    {
                        Id = item.Id,
                        City = foundContact != null ? foundContact.City : null,
                        State = foundContact != null ? foundContact.State : null,
                        Country = foundContact != null ? foundContact.Country : null,
                    };
            })

But remember that if your Contact item is struct - checking for null isn't proper way. Use Any() operator instead of FirstOrDefault().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜