chiapa
chiapa

Reputation: 4412

Error on applying linq to List

I am trying to create a sublist from a larger list using linq

List<ScenarioDetailModel> chartScenarioDetailsList = new List<ScenarioDetailModel>();

List<ScenarioDetailModel> subList = new List<ScenarioDetailModel>();
subList = chartScenarioDetailsList.Where(s => s.Code == "C3");

Both chartScenarioDetailsList and subList are of the same type but the compiler complains about type conversions and won't compile, the error is as follows:

Error 190 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)

However, it compiles when I change the sublist's type from List to IEnumerable:

IEnumerable<ScenarioDetailModel> subList = new List<ScenarioDetailModel>();
subList = chartScenarioDetailsList.Where(s => s.Code == "C3");

My question is: why does this happen?

Upvotes: 0

Views: 608

Answers (2)

John Castleman
John Castleman

Reputation: 1561

var subList = chartScenarioDetailsList.FindAll(s => s.Code == "C3");

But you really should embrace the IEnumerable concept, as suggested by others in comments and answers:

// I temporarily need a local sub-list to do something
// Approach 1 (older list approach)

{ // scope of subList
    var subList = chartScenarioDetailsList.FindAll(s => s.Code == "C3");
    foreach (var detail in subList)
    { /* do a thing with detail */ }
} // end of scope

// Approach 2 (enumerable approach)

foreach (var detail in chartScenarioDetailsList.Where(s => s.Code == "C3"))
{ /* do a thing with detail */ }

If your use of the sub-list is immediate and temporary, you can skip it altogether, and just iterate over the Where result.

Upvotes: 0

Waterfrag
Waterfrag

Reputation: 514

Where() does return an IEnumerable, not a List.

Try subList = chartScenarioDetailsList.Where(s => s.Code == "C3").ToList();

Also, you should assign subList directly with

chartScenarioDetailsList.Where(s => s.Code == "C3").ToList();

and not with new, since by doing so you're losing the reference created by your call to new.

Upvotes: 3

Related Questions