Why does the IEnumerable<T>.Select() works in 1 of 2 cases ? Can not be inferred from usage

Elisabeth picture Elisabeth · Jan 7, 2011 · Viewed 17k times · Source

I get this error message:

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.

The first method has no problems using a IEnumerable<T>.Select() ? Where is the problem with the 2nd method?

private void GetPupilsForSchoolclass()
{
   ObservableCollection<PupilViewModel> pupilsOC = new ObservableCollection<PupilViewModel>
   (                            _adminRepo.GetPupilsBySchoolclassId(_selectedSchoolclass.SchoolclassId).Select(p => new       PupilViewModel(p, _adminRepo))
   );
   SelectedSchoolclass.PupilListViewModel = pupilsOC;
}

private void GetDocumentsForPupil()
{
                ObservableCollection<Document> documentsOC = new ObservableCollection<Document>();
                IEnumerable<Document> documents = _docRepo.GetDocumentsByPupilId(_selectedPupil.Id);
                documents.Select(doc => documentsOC.Add(doc));
                SelectedPupil.Documents.DocumentList = documentsOC;
}

Answer

SLaks picture SLaks · Jan 7, 2011

documentsOC.Add returns void.
It doesn't make any sense (and is impossible) to write .Select<Something, void>(...).

What you're trying to do cannot work in the first place; Select is lazy and doesn't call your function until you enumerate the results.

You should use a regular foreach loop.