2010-01-20 43 views
4

我使用下面的代码返回一个IList:LINQ的转换

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 1[<>f__AnonymousType0 1 [System.String]]'键入'System.Collections.Generic.IList`1 [System.String]'。

我应该回到这里吗?

回答

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(); 
    } 
+0

哎哟.....不知道我是如何错过的......我以为我**有**使用**新**运算符返回一列。 – vikasde 2010-01-20 17:56:49

0

试试这个:

return query.ToList<string>(); 
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()将不是必需的。