gpt4 book ai didi

c# - 无法从用法中推断出 SelectMany 类型参数

转载 作者:行者123 更新时间:2023-11-30 12:23:58 24 4
gpt4 key购买 nike

我有一个 Controller ,上面有一些操作,其中一些可能有自定义属性。我想使用 linq 为 Controller 上的每个操作选择一些数据为匿名类型,例如

    Controller1
Action1
[MyAttribute("Con1Action2)"]
Action2
[MyAttribute("Con1Action3")]
Action3


Controller2
Action1
[MyAttribute("Con2Action2)"]
Action2
[MyAttribute("Con2Action3")]
Action3

我想要返回以下内容:

NameSpace = "someText", Controller = "Controller1", ActionName = "Con1Action2", 
NameSpace = "someText", Controller = "Controller1", ActionName = "Con1Action3",
NameSpace = "someText", Controller = "Controller2", ActionName = "Con2Action2",
NameSpace = "someText", Controller = "Controller2", ActionName = "Con2Action3"

我正在努力为每个操作选择一个 SelectMany:

var controllers= myControllerList
.Where(type =>type.Namespace.StartsWith("X.") &&
type.GetMethods().Any(m => m.GetCustomAttributes(typeof(MyAttribute)).Any()))
.SelectMany(type =>
{
var actionNames = type.GetMethods().Where(m => m.GetCustomAttributes(typeof(MyAttribute)).Any()).ToList();

var actionName = (MyAttribute)actionNames[0].GetCustomAttribute(typeof(MyAttribute));
return new
{
Namespace = GetPath(type.Namespace),
ActionName= actionName.Name,
Controller = type.Name.Remove(2);
};
}).ToList();

我在 SelectMany 上遇到错误 - 该方法的类型参数...无法从用法中推断出来。

最佳答案

“SelectMany 将序列的每个元素投影到 IEnumerable,并将结果序列展平为一个序列。”来源:https://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany(v=vs.100).aspx

您要返回一个元素:

return new
{
Namespace = GetPath(type.Namespace),
ActionName= actionName.Name,
Controller = type.Name.Remove(2);
};

你可以只使用.Select

如果您想从作为集合的属性中获取扁平列表,您可以使用 SelectMany,例如:

projects.SelectMany(p => p.Technologies).ToList()

假设一个项目有一个名为 Technologies 的集合的属性,该查询将返回所有项目的所有技术。

在你的例子中,因为你想要每个 Controller 的 Action 列表,你必须返回每个 Controller 的 Action 信息列表:

var controllers= myControllerList
.Where(type =>type.Namespace.StartsWith("X.") &&
type.GetMethods().Any(m => m.GetCustomAttributes(typeof(MyAttribute)).Any()))
.SelectMany(type =>
{
var actionNames = type.GetMethods().Where(m => m.GetCustomAttributes(typeof(MyAttribute)).Any()).ToList();

return actionNames.Select(action => {
var actionName = (MyAttribute)action.GetCustomAttribute(typeof(MyAttribute));
return new
{
Namespace = GetPath(type.Namespace),
ActionName= actionName.Name,
Controller = type.Name.Remove(2);
});
});
}).ToList();

关于c# - 无法从用法中推断出 SelectMany 类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35221532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com