Adrakadabra
Adrakadabra

Reputation: 599

question about linq select and ToList()

I have a problem with returning a list by executing a Select LINQ query. This is the query:

 var data = Repository<EducationString>
              .Find()
              .ToList() 
              .Select(p => new EducationStringModel() {
                      Id = p.Id,
                      Title = p.Title,
                      EducationDegree=p.EducationDegree })
              .ToList();

As you can see I used ToList() 2 times. I don't know why but when I delete the first ToList() I see this error, "Index was outside the bounds of the array", but by having both ToList() there is no problem.

Would it help if I said EducationDegree in EducationStringModel is an IList<EducationDegree>?

Is there anybody who knows the reason?

@Mark :its L2O

if u need to see the classes:

public class EducationStringModel { private IList _educationDegree = new List(); public IList EducationDegree { get { if (_educationDegree == null) { _educationDegree = new List(); } return _educationDegree; } set { _educationDegree = value; }

}

public int? Id { get; set; }
public string Title { get; set; }

}

public class EducationString{

private string _title; private IList _educationExperiences; private IList _educationDegree;

virtual public string Title
{
    get { return _title; }
    set { _title = value; }
}

virtual public IList<EducationExperience> EducationExperiences
{
    get
    {
        if (_educationExperiences == null)
        {
            _educationExperiences = new List<EducationExperience>();
        }

        return _educationExperiences;
    }

    set
    {
        _educationExperiences = value;
    }

}

virtual public IList<EducationDegree> EducationDegree
{
    get
    {
        if (_educationDegree == null)
        {
            _educationDegree = new List<EducationDegree>();
        }
        return _educationDegree;
    }

    set
    {
        _educationDegree = value;
    }
}

}

Upvotes: 3

Views: 3000

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064104

Is that the actual code? The only unclear thing there is: what does Find() return?

It sounds like the ToList is helping here by breaking composition and using LINQ-to-Objects, in which case AsEnumerable() should work just as well. After that you just do a Select (which for L2O just takes each item in turn and applies the map). If Find() is something more exotic, it sounds like a bug in that LINQ provider (or perhaps more fairly: that provider struggling to cope with an atypical construct). Hard to say more without a fully reproducible example.

Upvotes: 3

Related Questions