I have tables Message
and Image
that I'm joining. The tables look like this:
Message(MessageID, TimeStamp, Text, RoomID, ImageID, UserID)
Image(ImageID, Path, Type, UserID)
Not all messages will have an ImageID
. Here's my current join:
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
};
I then bind resultTable
to a ListView
that needs the Path
column from the Image
table. My current join only returns messages with images. How would I select all messages, but if the message has an ImageID != null
, then assign it a value for Path
? I assume I should change this line: on m.ImageID equals i.ImageID
at minimum.
It will return an empty enumerable. It won't be null.
In LINQ, an inner join is used to serve a result which contains only those elements from the first data source that appears only one time in the second data source. And if an element of the first data source does not have matching elements, then it will not appear in the result data set.
NULL in SQL means, "value absent, will match any comparison", whereas null in . NET means "no object, comparing against null will always yield false". Save this answer.
The group join is useful for producing hierarchical data structures. It pairs each element from the first collection with a set of correlated elements from the second collection. For example, a class or a relational database table named Student might contain two fields: Id and Name .
You're currently doing an inner join, but you can use DefaultIfEmpty() to create a left outer join. This will also return the null records.
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 : ""
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With