Linq转换
我使用以下代码返回 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.List1[<>f__AnonymousType0
1[System. String]]' 以键入“System.Collections.Generic.IList`1[System.String]”。
我应该返回这里什么?
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__AnonymousType0
1[System.String]]' to type 'System.Collections.Generic.IList`1[System.String]'.
What I am supposed to return here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
只要 q.code 是一个字符串,这应该可以工作:
请注意,它并没有创建匿名对象,只是选择了字符串。
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.
您选择匿名类型有什么原因吗?如果没有尝试这个...
Is there a reason you were selecting an anonymous type? If not try this...
怎么样
Or
?但是我假设
q.Code
是一个字符串?在这种情况下,您只想更改 LINQ 表达式:How about
Or
But I'm assuming that
q.Code
is a string? In which case you just want to change your LINQ expression:在查询中,无需选择包含字符串的匿名类,只需选择字符串本身:
In the query, instead of selecting an anonymous class containing a string, just select the string itself:
您不能将自定义类型列表转换为这样的字符串列表。最简单的方法是让您的
query
对象以 iEnumerable 字符串列表(而不是自定义类型)的形式开始其生命周期。将您的选择行更改为:select new q.Code.toString();
就可以了。如果 q.Code 本身就是一个字符串开头,则不需要
.ToString()
。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.试试这个:
Try this: