1

I am new to async programming. FirstOrDefaultAsync is throwing an error

List does not contain a definition for FirstOrDefaultAsync()

Can someone explain me what I am doing wrong?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace PatientManagement.Models
{
    public class PatientService : IPatientService
    {
        private List<Patient> patients;

        public PatientService()
        {
            patients = new List<Patient>()
            {
                new Patient(){ ID = 1, Name = "Akash", Email = "aakash1027@gmail.com" },
                new Patient(){ ID = 2, Name = "John", Email = "John@gmail.com" },
                new Patient(){ ID = 3, Name = "Mike", Email = "Mike@gmail.com" },
            };
        }

        public async Task<Patient> GetPatient(int id)
        {
            return await patients.FirstOrDefaultAsync(x => x.ID == id);
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Does this answer your question? [IEnumerable does not contain definition for FirstOrDefaultAsync()](https://stackoverflow.com/questions/55755534/ienumerablemovies-does-not-contain-definition-for-firstordefaultasync) – Allen Chen Jun 12 '21 at 16:22

1 Answers1

0

The problem is there really is no FirstOrDefaultAsync method on a List!

Async code is appropriate for cases where you, for instance, cross a boundary and have to wait for a database or some other process to do work. Your case is different: your process actually has to do the work of finding this record in the list. So you should just use the normal synchronous FirstOrDefault:

    public Patient GetPatient(int id)
    {
        return patients.FirstOrDefault(x => x.ID == id);
    }
Brian MacKay
  • 31,133
  • 17
  • 86
  • 125