none
Invalid Cast Exception RRS feed

  • Question

  • I wrote the following code

     

     

    var query = (from xxxxx)
              select xxxx);
          Decimal q;
    
    q = System.Convert.ToDecimal(query);
    

    but I receive the following message

    Unable to cast object of type 'System.Data.Linq.DataQuery`1[System.String]' to type 'System.IConvertible'.

     

    I have the same code in a method above which takes 3 arguments instead of 1 (I overriden the method) and I didnt have this problem.

     

    Sunday, January 2, 2011 2:00 PM

Answers

  • Hi,

    In your code, query will return a collection. It looks that you probably need the first record returned by your query. This can be achieved  by using the First/Single/Last method like this:

    decimal q = System.Convert.ToDecimal( query.First() );
    

     

    Regards,


    Syed Mehroz Alam
    My Blog | My Articles
    Monday, January 3, 2011 5:50 AM

All replies

  • Hi,

    In your code, query will return a collection. It looks that you probably need the first record returned by your query. This can be achieved  by using the First/Single/Last method like this:

    decimal q = System.Convert.ToDecimal( query.First() );
    

     

    Regards,


    Syed Mehroz Alam
    My Blog | My Articles
    Monday, January 3, 2011 5:50 AM
  • What you should understand here is that although your query may only have one result, the system doesn't know if there are zero one or n items returned by that query.  You can use the extension methods that Syed suggested or you can also you the indexing such as query[0].
    Tuesday, January 4, 2011 7:27 PM