Haikal Nashuha
Haikal Nashuha

Reputation: 3048

Nested Select in LINQ with Lambda Expression

I have two sequence of objects; namely Messages for Message object and Newsflashes for Newsflash object.

Both are derived through Entity Framework ADO.NET Entity Model. The diagram of the model is as below: enter image description here

As you can see, the Newsflash inherits from Message. However, the generated Index in the controller somehow error and I need to do manual query to pass the right sequence to the View.

The Newsflash table only has one column, which is Id and at the same time a foreign key to the Message Id. I want to query like this in LINQ SELECT * FROM MESSAGE WHERE ID IN (SELECT ID FROM NEWSFLASH)

So far I have tried something like this: var message = Messages.Where(x => x.Id == Newsflash.Any(y=>y.Id))

But I am getting error that cannot convert int to bool. What did I do wrong? How do nested select especially from a list is handled in LINQ? How can I access element in the sequence; in this case Newsflash so that I could get the Id individually?

Upvotes: 0

Views: 7032

Answers (2)

Kevin Nacios
Kevin Nacios

Reputation: 2853

Any returns a bool, not a list of values. If you want a list of Newsflash ID's, you would use Newsflash.Select(x => x.Id)

To get your list of messages that have a newsflash, you should use:

var messages = (from m in Messages
                join n in Newsflash on m.Id equals n.Id
                select m).ToList();

This will join messages to your newsflash based on the Id for each, and then select the Message object that matches.

alternative lamba syntax:

var messages = Messages.Join(Newsflash, x => x.Id, y => y.Id, (x, y) => new { Message = x }).ToList();

Upvotes: 2

crackhaus
crackhaus

Reputation: 1196

If newsflash is just a list of Ids Try this.

var message = Messages.Where(x => Newsflash.Contains(x.Id));

or

var message = Messages.Where(x => Newsflash.Select(y => y).Contains(x.Id));

simple example.

var listOfInts = new List<int>{1,2,3,4,5,6,7,8,9,10};
var listOfInts2 = new List<int>{1,2,3,4,5};

listOfInts.Where(x => listOfInts2.Contains(x));

Upvotes: 2

Related Questions