Search code examples
c#.netlinqanonymous-types

Adding Selected Properties to List and return as API Call in C#


I am getting a list of object as a return from function call. I want to add only few properties of object to anonymous object and return it. Can you please let me know how to do?

var destinationSelectedProperties = new { code = string.Empty, name = string.Empty };
var destinations = pricerepository.GetDestinationsBasedOnMarketAndProgram(salesItemRequest);

if (destinations == null || !destinations.Any())
    return StatusCode(StatusCodes.Status204NoContent);

destinations.ToList().ForEach(u => {
                destinationSelectedProperties = new
                {
                    code = u.Code,
                    name = u.Name
                };
            });

The code is as shown above. Here the code returns only the last value in the object as shown below

{
    "code": "US-WAS",
    "name": "Washington, D.C."
}

If the list has 3 values, I want to return all the values of the list as shown below:

[
{
    "code": "US-WAS",
    "name": "Washington, D.C."
},
{
    "code": "US-SSS",
    "name": "London"
},
{
    "code": "US-GBL",
    "name": "Global"
}
]

Solution

  • instead of single variable, we can get the anonymous object's list, and return it directly.

     // we need to comment it as its a single variable, 
     //var destinationSelectedProperties = new { code = string.Empty, name = string.Empty };
    
    var destinations = pricerepository.GetDestinationsBasedOnMarketAndProgram(salesItemRequest);
    
    if (destinations == null || !destinations.Any())
        return StatusCode(StatusCodes.Status204NoContent);
    
    return destinations.Select(u =>new
                    {
                        code = u.Code,
                        name = u.Name
                    }).ToList();