Tuesday, July 10, 2012

C# - Linq - Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'int'


Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'int'

Issue:
In Linq queries sometimes you get the exception "Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'int'". A scenario where you find this exception is as illustrated below:

int domainId = from p in pages
               where p.Value.aspxFile == pageFileName
               select p.Value.domain;

Logically I know there will only be one value being returned from this Linq Query statement, so it should work for me. But by syntax, this Linq statement returns type IEnumerable Collection.

Solution:

int domainId = (from p in pages
        where p.Value.aspxFile == pageFileName
        select p.Value.domain).First();

This solves my issue and it will return only one object and not a collection. The object type is determined by the compiler at compile time which will be int in my case.

You can use .First() or FirstOrDefault() or Single(). But for Single() make sure that there is exactly only one element in the list.

No comments:

Post a Comment