将 Linq ObjectQuery IQueryable 转换为 IEnumerable

5

我对这里所需的数据类型感到完全困惑。

我有这个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>'   

我找不到将数据转换为正确类型所需的语法。有人能帮忙吗?

谢谢, Matt

4个回答

8
编译时错误显示,feat是“字符串的IEnumerable的IQueryable的集合”(字面意思)。因此,您需要生成一个扁平的集合。
feat.SelectMany(x => x)

1
答案一直在我脸前盯着我,我试了各种 SelectMany() 技巧,但都没用。此外..这个答案非常难在谷歌上找到! - Tobias J

1

System.Data.Objects.ObjectQuery<T>System.Linq.IQueryable<T> 的一种实现。然而,您的类型是一个 IQueryable 的 IEnumerable 对象。执行 SelectMany 操作,这样您就不再拥有字符串集合的集合,而只是一个字符串集合。


0

你可以使用

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

我没有给你点踩,但是这个代码不起作用。你需要使用SelectMany()来展开集合。 - Rap

0

根据您需要对列表执行的操作,您可以直接执行:

var itemTypes = feat.ToList();

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