LINQ类型的参数不能从select中的用法推断出来
本文关键字:用法 推断出 select 类型 参数 不能 LINQ | 更新日期: 2023-09-27 18:26:30
objectiveData所在的位置如下: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();
}
我在线路上收到一个错误,"选择"说:
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.
这是我的目标类:
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; }
}
您需要
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
}
);
}
//you miss this
return result;
});
首先,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;
});
然而,为了以更常规的方式进行操作,我会这样做:
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 }));