C# How to get specific item from nested array

Viewed 4257

I have the following model:

public class Car
{
   public string Id {get; set;}
   public IList<Driver> Drivers {get; set;}
}

public Driver 
{
   public string Id {get; set;}
   public bool IsActive {get; set;}
}

How can I select driver that is active?

var carId = "...";
var activeDriver = await _carCollection.Find(a => a.Id == carId
            && a.Drivers.Any(e=>e.IsActive))
            .Project(a=>a.Drivers)
            .SingleOrDefaultAsync();

This code returns IList<Driver>, so all items. But I want to retrieve only one Driver that is active.

2 Answers

The above accepted answer did not work for me. It returned nothing. You can use the following code:

var activeDriver = await _carCollection.AsQueryable().Where(a => a.Id == carId).SelectMany(a => a.Drivers).Where(e => e.IsActive).FirstOrDefault();

You can check this link

Related