0

I want to be able to create an extension method to convert a list of one type to a list of another type.

 IEnumerable<Entity> EntityList = EntityData.GetAll();
 IEnumerable<ViewModel> = EntityList.ToViewModel();

I want to create the ToViewModel method but I'm not sure how to go about that.

Jack Tyler
  • 509
  • 6
  • 18

3 Answers3

2

You can write your own extension method

public static class LinqExtension
{
    public static IEnumerable<ViewModel> ToViewModel(this IEnumerable<Entity> source)
    {
        // your own conversion from Entity to ViewModel
        return result;
    }
}

Then you are able to use EntityList.ToViewModel()

Liu
  • 970
  • 7
  • 19
0

I figured it out. All I needed to do was create a static class with static methods inside that uses the 'this' keyword to get the parameter from the object your referencing.

for example:

 public static class Mapper
 {
     public static IEnumerable<ViewModel> ToViewModelList(this IEnumerable<Entity> entities)
     {
          return entities.Select(ToViewModel);
     }

     public static ViewModel ToViewModel(this Entity entity) 
     {
          return new ViewModel() {
              // Include mapping inside here    
              Id = entity.Id;
          };
     }

 }
Jack Tyler
  • 509
  • 6
  • 18
  • So your question boils down to "how to write an extension-method", making this a duplicate of e.g. https://stackoverflow.com/questions/1188224/how-do-i-extend-a-class-with-c-sharp-extension-methods – MakePeaceGreatAgain Jan 23 '19 at 11:16
0

Isn't that obvious? You need to loop through the items of the first list and convert them into the payload of the second list, then add them to newly created one, something like the following:

public List<ViewModel> toViewModel(List<Entity> entityList) {
        List<ViewModel> response = new ArrayList();
        for (Entity entity : entityList) {
            ViewModel viewModel = entity.convertToViewModel();
            response.add(viewModel);                
        }
        return response;
    }

It's worth mentioning that in this example the conversion actually happens on the item level, not the list so it is your source item which need be modified if you decide to go this way.

smoczyna
  • 489
  • 6
  • 18