Why does the IEnumerable.Select() works in 1 of

2019-02-22 17:02发布

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

5条回答
Animai°情兽
2楼-- · 2019-02-22 17:39

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.

查看更多
叛逆
3楼-- · 2019-02-22 17:40

I suspect that Add returns void - is that right? If so there is no way of projecting that to a Func<,> - only to an Action<T> - and Select wants the Func<,>.

Select is not the same as an indirect `foreach

查看更多
Luminary・发光体
4楼-- · 2019-02-22 17:43

Select is not a replacement for a foreach. Use this instead:

ObservableCollection<Document> documentsOC = new ObservableCollection<Document>();
IEnumerable<Document> documents = _docRepo.GetDocumentsByPupilId(_selectedPupil.Id);
foreach(var doc in documents)
{
    documentsOC.Add(doc);
}
SelectedPupil.Documents.DocumentList = documentsOC;
查看更多
手持菜刀,她持情操
5楼-- · 2019-02-22 17:53

The Error seems The Return statement missing when you select an Items from the collection.

Example:

collection = nonLabors.Select(item =>
                {
                    item.Travel_Miles = item.Travel_Miles_Original != null ? decimal.Parse(item.Travel_Miles_Original) : 0;
                    return item;
                }).ToList();
查看更多
forever°为你锁心
6楼-- · 2019-02-22 17:56

What is the return type of ObservableCollection<Document>.Add? Typically an Add method returns void. You can't use LINQ Select to execute a procedure for all elements, only a function that returns something (else where would the return value of Select come from?). Instead you can use LINQ ForEach or the C# foreach loop.

查看更多
登录 后发表回答