15

I am trying to do something like this...

public static List<string> GetAttachmentKeyList()
{
    DataClassesDataContext dc = new DataClassesDataContext();

    List<string> list = from a in dc.Attachments
        select a.Att_Key.ToString().ToList();

    return list;
}

Visual Studio is saying...

Cannot implicitly convert type 'System.Linq.IQueryable>' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)

What is the proper syntax???

MalamuteMan
  • 151
  • 1
  • 1
  • 4

3 Answers3

23

Give this a try

public static List<string> GetAttachmentKeyList()
{
    DataClassesDataContext dc = new DataClassesDataContext();

    List<string> list = ( from a in dc.Attachments
                          select a.Att_Key.ToString() ).ToList();

    return list;
}
Brian Dishaw
  • 5,767
  • 34
  • 49
  • 3
    +1: Yes, in the original sample the `.ToList()` was called on the string returned by `ToString()`, so the linq expression evaluated to - _something like_ - `IEnumerable>`, not `List` – Binary Worrier Sep 20 '11 at 17:15
  • THANKS Brian & Praveen for your helpful and incredibly FAST replies!!!! That did the trick. – MalamuteMan Sep 20 '11 at 17:43
  • 1
    This is the simplest correction to the code in the question; however [Pedro's answer](https://stackoverflow.com/a/7489012/199364) is more succint. – ToolmakerSteve Dec 27 '17 at 22:31
12

try this,

public static List<string> GetAttachmentKeyList()
{
    DataClassesDataContext dc = new DataClassesDataContext();

    return dc.Attachments.Select(a=>a.Att_Key).ToList();
}
Pedro Costa
  • 2,968
  • 2
  • 18
  • 30
2

I guess it would something like below.

       List<string> list = (from a in dc.Attachments
                             select a.Att_Key.ToString()).ToList<string>();

Hope this helps!!

Praveen
  • 1,449
  • 16
  • 25
  • 1
    Can we do without the Whole Paranthesis `(from...).ToList()` – Gokul E Jan 04 '14 at 10:58
  • @GokulE, those parentheses are needed, to know what `ToList` is being applied to - the result of that whole expression. Notice that in the original question, code was attempted, but those parentheses were missing. This applied `ToList` to a single string, inside the `select` clause. OR see Pedro's answer, for a simpler solution. – ToolmakerSteve Dec 27 '17 at 22:27