简体   繁体   中英

How to remove list object from an item in List?

I have a class:

public class FlightDetails
{
    public string FlightId {get; set;}
    public string PilotName {get; set;}
    public string Area {get; set;}
    public string Country {get; set;}
}

Here sending response:

public async Task<List<FlightDetails>> GetFlightAsync(string FlightId)
{
    //
    var flights = new List<FlightDetails>();
    flights = response.AllFlights;
    flights = flights.Where(x => x.FlightId.Contains(FlightId)).ToList();
    //
    return flights;
}

Getting List here and data is filled but issue is don't want FlightId and Country in the response which I am sending. How to remove this objects in the List ? Finally in the List item there should be only PilotName and Area .


Update:

I forgot the following line before the flights = response.AllFlights;:

    var request = await _rest.Get<WorldFlights>(url + $"?FlightId={FlightId}");

You will need to create another object, and map there only the properties you want. For example:

public class FlightDetailsResponse
{
    public string PilotName {get; set;}
    public string Area {get; set;}
}

And then in the function:

public async Task<List<FlightDetailsResponse>> GetFlightAsync(string FlightId){
    
    var flights = response.AllFlights;
    var flightResponses = flights
        .Where(x => x.FlightId.Contains(FlightId).ToList())
        .Select(x => new FlightDetailsResponse{
            PilotName = x.PilotName,
            Area = x.Area
        });
    
    return flightResponses;
}

This way the response will only contain the PilotName and Area fields.

PD: What I wrote might not compile because of missing commas or something like that. Sorry, it has been some time since I last wrote C#, but the idea is that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM