2010-12-01 70 views
5

完全混淆了这里所需的数据类型。将Linq ObjectQuery IQueryable转换为IEnumerable

我有这样的LINQ声明:

   var feat = AllCustomers 
        .Select(c => c.CustomerServices.SelectMany(cs => cs.CustomerServiceFeatures) 
        .SelectMany(csf => csf.ConfigElements).Where(ce => ce.Name == "ItemType").Select(ce => ce.Value).Distinct()); 

它返回所需的数据,并VS告诉我,类型被设定为:

System.Data.Objects.ObjectQuery<System.Collections.Generic.IEnumerable<string>> 

但是我想这个数据添加到字符串列表:

List<string> itemTypes = new List<string>(); 
itemTypes.AddRange(feat); 

但是,这将引发一个错误:

Argument 1: cannot convert from 'System.Linq.IQueryable<System.Collections.Generic.IEnumerable<string>>' to 'System.Collections.Generic.IEnumerable<string>' 

我无法找到所需的语法来转换为正确的类型。谁能帮忙?

干杯, 马特

回答

8

编译时错误显示, feat是“字符串集合的集合”(字面意思是“IEnumerable of string”的IQueryable)。所以你需要生成平面集合。

feat.SelectMany(x => x) 
+1

答案在整个这段时间里,我一直在面对着我,我正在尝试各种各样的SelectMany()技巧,除此之外。另外..这个答案是非常困难的谷歌! – 2012-02-13 21:08:25

0

可以使用

List<string> list = feat.ToList<string>() 
+0

我没有downvote你,但这是行不通的。你需要SelectMany()来压扁集合。 – Rap 2013-09-19 17:11:30

0

根据您需要的名单做什么,你可以这样做:

var itemTypes = feat.ToList(); 
1

System.Data.Objects.ObjectQuery<T>System.Linq.IQueryable<T>的执行。但是,您的类型是IEnumerable对象的IQueryable。执行一个SelectMany,所以你不再有一个字符串集合的集合,而只是一个字符串的集合。

相关问题