user3900520
user3900520

Reputation: 71

Two LINQ queries returning different data types

I come to you in desperate need of help today. I have two tables named setup and channels which have a many-to-one relationship. Many channels belong to one setup. At any given time only one setup is active. I am trying to query my database and get only the channels belonging to the active setup. The query I have works, but returns an IEnumerable when I need a list. Yet I use a similar query to just get all the channels, and it returns a list. What can I do to get a list?

This query returns a List like I expect:

var q = (from a in DTE.channels
                     select a).ToList();
this.myChannels = new ObservableCollection<channel>(q);

This query, which provides the filtered data I want, returns an IEnumerable even though I call ToList(), and my ObservableCollection doesn't like IEnumerables:

var f = (DTE.setups.Where(m => m.CurrentSetup == true).Select(m => m.channels)).ToList();
this.myChannels = new ObservableCollection<channel>(f);

Any help is very, very appreciated. Thank you and have a nice day.

Upvotes: 0

Views: 211

Answers (1)

Sergey Litvinov
Sergey Litvinov

Reputation: 7458

Posting my comment as answer as it helped. Your problem is that you have many to many relationship, so your .Select(m => m.channels) actually returns not List<channel>, but list of lists - List<List<channel>> as each record has own list, and it just returns these lists.

You just need to use .SelectMany(m => m.channels).ToList() instead .Select and SelectMany will get returned lists and will combine them into one list with all data. So you will have List<channel> as you need.

Upvotes: 2

Related Questions