LINQ type arguments cannot be taken out of use in the selected

I have the following where objectData: 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 get an error in a line labeled "select":

 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 is 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; } } 
+7
c # linq
source share
3 answers

You need

 return result; 

at the end of your expression.

+11
source share
 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; }); 
+1
source share

First of all, LINQ and side effects ... well, bad. Due to lazy loading and many other issues. However, you need to add the line return result; at the end of your code, for example:

 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, in order to behave more regularly, I would do it as follows:

 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 })); 
0
source share

All Articles