10

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

3 回答 3

19

你需要

return result;

在你的表达结束。

于 2013-08-05T10:23:58.290 回答
2
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;
    });
于 2013-08-05T10:23:52.210 回答
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 }));
于 2013-08-05T10:25:00.777 回答