LINQ - 类型参数不能从select中的用法推断出来

时间:2013-08-05 10:21:17

标签: c# linq

我有以下其中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; }
}

3 个答案:

答案 0 :(得分:14)

你需要

return result;

在表达结束时。

答案 1 :(得分:1)

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;
    });

答案 2 :(得分:0)

首先,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 }));