Huma Ali
Huma Ali

Reputation: 1809

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable Cast error

I have the following model classes. I want to retrieve object of AddressMatch from AddressMatches list based on some condition.

public class AddressMatchList
{
    public List<AddressMatch> AddressMatches { get; set; }
}

public class AddressMatch
{
    public string HouseRange { get; set; }
    public string HouseNumber { get; set; }
    public string StreetName { get; set; }
    public string AddressIdentifier { get; set; } 
}

I tried this:

AddressMatch selectedMatchedAddress = new AddressMatch();   
selectedMatchedAddress = addressMatches.AddressMatches.Where(a => a.AddressIdentifier == "cpr");

But got error:

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

Upvotes: 2

Views: 6665

Answers (3)

A3006
A3006

Reputation: 1069

List<AddressMatch> a1 = addressMatches.AddressMatches
                        .Where(a => a.AddressIdentifier == "cpr")
                        .ToList<AddressMatch>();

Where returns an IEnumerable of items, which is not compatible with List<AddressMatch>. The ToList<AddressMatch>() method at the end creates a compatible list from the IEnumerable created by Where.

Upvotes: 0

MrVoid
MrVoid

Reputation: 709

That's because in the LINQ expression

.Where(a => a.AddressIdentifier == "cpr")

There is no way of know if the result of it will be one item o several items, the result of that will be a Enumerable<T>.

You can use FirstOfDefault() to make sure the expressions only returns a item of AddressMatch`.

.Where(a => a.AddressIdentifier == "cpr").FirstOfDefault();

Upvotes: 3

Patrick Hofman
Patrick Hofman

Reputation: 156918

The Where returns an enumerable (list of) items, where you expect just one.

You could use this if you want to make sure there is just one matching (SingleOrDefault will give an exception if more than one matching item is found):

selectedMatchedAddress = addressMatches.AddressMatches
                         .SingleOrDefault(a => a.AddressIdentifier == "cpr");

Or this if you just want the first matching item:

selectedMatchedAddress = addressMatches.AddressMatches
                         .FirstOrDefault(a => a.AddressIdentifier == "cpr");

In both cases it is important to check selectedMatchedAddress for null.

Upvotes: 7

Related Questions