Bri*_*n J 1 c# linq ienumerable list anonymous-types
我已经List<Application>使用 Linq 过滤了该列表中的两个字段并返回结果,现在需要将该列表返回给调用方法。
Linq 过滤的结果是 类型IEnumerable<AnonymousType>,因此我无法返回该结果,因为我的方法返回类型是List<Application>。
我首先尝试的是使用 ToList 方法转换 IEnumerable ,但这会引发编译器错误:
IEnumerable does not contain a definition for ToList()
Run Code Online (Sandbox Code Playgroud)
问题:
如何将 IEnumerable 转换或转换为 List ?
代码:
这是在列表上执行的赋值,以连接两个字段并将其作为列表返回:
var filteredAppList = applicationList.Select(c => new { c.RID, RID_APP_FIELD = c.RID + " " + c.BusinessFriendlyName });
Run Code Online (Sandbox Code Playgroud)
下面是我尝试将 IEnumerable 作为列表返回的方法:
return filteredAppList.ToList<Application>();
Run Code Online (Sandbox Code Playgroud)
问题是,前面的查询返回一系列匿名对象,我们正在尝试将它们转换为Application类型。这是导致问题的原因,请尝试此操作。
filteredAppList.Select(x=> new Application()
{
// set properties.
})
.ToList();
Run Code Online (Sandbox Code Playgroud)