C# LINQ - 无法从选择中的用法推断出类型参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18055802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ - type arguments cannot be inferred from the usage in a select
提问by
I have the following where objectiveData is: IEnumerable<Objective>
我有以下目标数据是: IEnumerable<Objective>
public IList<Objective> createObjectives()
{
var objectiveData = GetContent.GetType5();
var objectives = objectiveData.Select(o => {
var result = new Objective {
Name = o.Name,
Text = o.Text
};
if (o.Name != null && o.Name.EndsWith("01"))
{
result.ObjectiveDetails.Add
(
new ObjectiveDetail
{
Text = o.Text
}
);
}
});
return objectives.ToList();
}
I am getting an error on the line with the "select" saying:
我在“选择”行中收到错误消息:
The type arguments for method 'System.Linq.Enumerable.Select<TSource,TResult>
(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,int,TResult>)'
cannot be inferred from the usage. Try specifying the type arguments explicitly.
Here's my Objective class:
这是我的目标类:
public partial class Objective : AuditableTable
{
public Objective()
{
this.ObjectiveDetails = new List<ObjectiveDetail>();
}
public int ObjectiveId { get; set; }
public string Name { get; set; }
public string Text { get; set; }
public virtual ICollection<ObjectiveDetail> ObjectiveDetails { get; set; }
}
回答by King King
var objectives = objectiveData.Select(o => {
var result = new Objective {
Name = o.Name,
Text = o.Text
};
if (o.Name != null && o.Name.EndsWith("01"))
{
result.ObjectiveDetails.Add
(
new ObjectiveDetail
{
Text = o.Text
}
);
}
//you miss this
return result;
});
回答by Plymouth223
You need
你需要
return result;
at the end of your expression.
在你的表达结束时。
回答by It'sNotALie.
First of all, LINQ and side effects are... well, bad. Due to lazy loading, and many other issues. However, what you need is to add a return result;
line at then end of your code like so:
首先,LINQ 和副作用是......好吧,糟糕。由于延迟加载和许多其他问题。但是,您需要return result;
在代码的末尾添加一行,如下所示:
var objectives = objectiveData.Select(o => {
var result = new Objective {
Name = o.Name,
Text = o.Text
};
if (o.Name != null && o.Name.EndsWith("01"))
{
result.ObjectiveDetails.Add
(
new ObjectiveDetail
{
Text = o.Text
}
);
}
return result;
});
However, for this to behave in a more regular manner, I would do it like this:
但是,为了使其以更规律的方式表现,我会这样做:
var objectives =
objectiveData.Select(o => new Objective { Name = o.Name, Text = o.Text})
result.ObjectiveDetails.AddRange(
objectiveData.Where(o => (o.Name ?? "").EndsWith("01"))
.Select(o => new ObjectiveDetail { Text = o.Text }));