Linq转换

4
我正在使用以下代码返回一个IList:
```

我正在使用以下代码返回一个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();
        }

但是我一直遇到这个错误:

无法将类型为'System.Collections.Generic.List<code>1[<>f__AnonymousType01[System.String]]'的对象强制转换为类型'System.Collections.Generic.IList`1[System.String]'。

我应该返回什么?

6个回答

4
只要 q.code 是一个字符串,这个就可以工作: 请注意,它并没有创建一个匿名对象,只是选择了字符串。
    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();
    }

哎呀……我不确定我怎么错过了这个……我以为我必须使用“new”运算符来返回单列。 - vikasde

2

你选择匿名类型有什么原因吗?如果没有,可以尝试这样做...

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

1

怎么样?

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

或者

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

我假设q.Code是一个字符串? 如果是这样,您只需要更改LINQ表达式:

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

1
在查询中,不要选择包含字符串的匿名类,而是直接选择字符串本身:
var query = from q in session.Linq<Store>()
            where q.Country == country
            orderby q.Code
            select q.Code;

1

你不能像那样将自定义类型的列表转换为字符串列表。最简单的方法是让你的query对象一开始就成为一个iEnumerable字符串列表,而不是一个自定义类型。将你的选择行更改为:

select new q.Code.toString();

这样就可以了。如果q.Code本身就是一个字符串,那么.ToString()就不必要了。


0

试试这个:

return query.ToList<string>();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接