views:

225

answers:

6
+4  Q: 

Linq conversion

I am using the following code to return an IList:

public IList<string> FindCodesByCountry(string country)
        {
            var query = from q in session.Linq<Store>()
                        where q.Country == country
                        orderby q.Code
                        select new {q.Code};

            return (IList<string>) query.ToList();
        }

However I keep getting this error:

Unable to cast object of type 'System.Collections.Generic.List1[<>f__AnonymousType01[System.String]]' to type 'System.Collections.Generic.IList`1[System.String]'.

What I am supposed to return here?

A: 

Try this:

return query.ToList<string>();
Randy Minder
+4  A: 

as long as q.code is a string this should work: note that it is not creating an anonymous object, just the string is being selected.

    public IList<string> FindCodesByCountry(string country)
    {
        var query = from q in session.Linq<Store>()
                    where q.Country == country
                    orderby q.Code
                    select q.Code;

        return query.ToList();
    }
John Boker
ouch..... not sure how I missed that... I thought I **had** to use the **new** operator to return a single column.
vikasde
+2  A: 

Is there a reason you were selecting an anonymous type? If not try this...

    var query = from q in session.Linq<Store>()
                where q.Country == country
                orderby q.Code
                select q.Code;
Jace Rhea
+1  A: 

How about

query.Select(s => s.ToString()).ToList();

Or

query.Cast<String>().ToList();

But I'm assuming that q.Code is a string? In which case you just want to change your LINQ expression:

var query = from q in session.Linq<Store>()
                    where q.Country == country
                    orderby q.Code
                    select q.Code;
Dathan
+1  A: 

In the query, instead of selecting an anonymous class containing a string, just select the string itself:

var query = from q in session.Linq<Store>()
            where q.Country == country
            orderby q.Code
            select q.Code;
Mark Byers
+1  A: 

You can't cast a list of custom types to a list of strings like that. The easiest way would be to have your query object begin it's life as an iEnumerable list of strings, rather than a custom type. Change your select line to:

select new q.Code.toString();

and you'll be good. If q.Code is itself a string to begin with, then the .ToString() won't be necessary.

Patrick Karcher