Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?)

like image 899
Huma Ali Avatar asked May 08 '26 09:05

Huma Ali


2 Answers

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.

like image 188
Patrick Hofman Avatar answered May 10 '26 23:05

Patrick Hofman


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();
like image 25
MrVoid Avatar answered May 10 '26 21:05

MrVoid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!