1

I have a method that returns a list of Guids. I want the following linq query in it:

var results = (from t in CurrentDataSource.Table1
               where t.Manager == userId && t.Profile != null
               select t.Profile).ToList();

Why do I get the following error:

Error   4   Cannot implicitly convert type 'System.Collections.Generic.List<System.Guid?>' to 'System.Collections.Generic.List<System.Guid>'    
Tacy Nathan
  • 344
  • 1
  • 6
  • 15
  • 3
    Are you positive its being thrown from that line? It doesn't look like it is. –  Nov 02 '16 at 12:42
  • 1
    The error is telling you that you're trying to convert a `List` to a `List`, which can't implicitly be done. I don't see how this line of code would be causing that error though. – David Nov 02 '16 at 12:43
  • 1
    Possible duplicate of [Implicit convert List to List](http://stackoverflow.com/questions/14394016/implicit-convert-listint-to-listint) – GSerg Nov 02 '16 at 12:44
  • just select `t.Profile.Value` instead to get a `Guid` instead of `Guid?` since you already filter out the `null` ones. – juharr Nov 02 '16 at 12:47
  • 1
    Post the line where the compilation error occurs. This code won't throw that error. – Panagiotis Kanavos Nov 02 '16 at 12:51

2 Answers2

5

You're checking if t.Profile is null, and only returning valid Guid's, so an explicit cast should work:

var results = (from t in CurrentDataSource.Table1
           where t.Manager == userId && t.Profile != null
           select (Guid)t.Profile).ToList();
Blue
  • 22,608
  • 7
  • 62
  • 92
4

Because you can't cast/convert a List<Guid?> to List<Guid>. You can use:

var results = (from t in CurrentDataSource.Table1
               where t.Manager == userId && t.Profile != null
               select t.Profile.GetValueOrDefault()).ToList();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 1
    Shouldn't `ToList()` return a `List` without causing a compilation error? This code doesn't show any conversions between lists, unless `t.Manager` and `userId` are lists of GUIDs – Panagiotis Kanavos Nov 02 '16 at 12:51
  • @PanagiotisKanavos: sure, the shown code compiles. But OP does something with this `List`, for example returning it as a `List` or assigning it to a variable of that type. That code will not compile. – Tim Schmelter Nov 02 '16 at 13:05
  • Fails against IQuerable though: LINQ to Entities does not recognize the method 'System.Guid GetValueOrDefault()' method, and this method cannot be translated into a store expression. An explicit cast however works. – Tacy Nathan Nov 02 '16 at 13:06