我有加入的Message
和Image
表格。表格如下所示:
Message(MessageID, TimeStamp, Text, RoomID, ImageID, UserID)
Image(ImageID, Path, Type, UserID)
并非所有邮件都会有ImageID
。这是我目前的加入:
List<Message> messages = Message.GetAll();
List<Image> images = Image.GetAll();
var resultTable = from m in messages
join i in images
on m.ImageID equals i.ImageID
select new
{
MessageID = m.MessageID,
TimeStamp = m.TimeStamp,
Text = m.Text,
RoomID = m.RoomID,
ImageID = m.ImageID,
UserID = m.UserID,
Path = i.Path // Nullable
};
然后我将resultTable
绑定到需要ListView
表中的Path
列的Image
。我当前的连接仅返回带有图像的消息。如何选择所有邮件,但如果邮件包含ImageID != null
,则为其分配Path
的值?我想我应该改变这一行:on m.ImageID equals i.ImageID
至少。
答案 0 :(得分:4)
您目前正在进行内部联接,但您可以使用DefaultIfEmpty() to create a left outer join。这也将返回空记录。
var resultTable = from m in messages
join i in images on m.ImageID equals i.ImageID into imgJoin
from img in imgJoin.DefaultIfEmpty()
select new
{
MessageID = m.MessageID,
TimeStamp = m.TimeStamp,
Text = m.Text,
RoomID = m.RoomID,
ImageID = m.ImageID,
UserID = m.UserID,
Path = img != null ? img.Path : ""
};