7

Is it possible in C# to do something similar to the following?

var tigerlist = new List<Tigers>(){ Tail = 10, Teeth = 20 };

var tigers_to_cats_approximation = new List<Cat>()
{    
     foreach (var tiger in tigerlist)
     {                 
           new Cat()
           {
               Tail = tiger.Tail / 2,
               Teeth = tiger.Teeth / 3,
               HousePet = true,
               Owner = new Owner(){ name="Tim" }
           }
     }
}

I'm doing some XML apis and the request objects coming in are similar to the response objects that need to go out. The above would be incredibly convenient if it were possible; much more so than auto-mapper.

Junaid Pathan
  • 3,850
  • 1
  • 25
  • 47
Watson
  • 1,385
  • 1
  • 15
  • 36
  • 6
    `var tigers_to_cats_approximation = tigerlist.Select(tiger => new Cat() { Tail = tiger.Tail / 2, Teeth = tiger.Teeth / 3, HousePet = true, Owner = new Owner(){name="Tim"} }).ToList();`? – Ousmane D. Jul 31 '18 at 18:28
  • You might consider creating a conversion method that takes in a `Tiger` and returns a `Cat` (i.e. `public Cat ConvertToCat(Tiger tiger) { return new Cat() { Tail = tiger.Tail / 2, Teeth = tiger.Teeth / 3, HousePet = true, Owner = new Owner() { name="Tim" } }; }`), which you could then call using a `Select` statement on the `tigerList`, like: `var catsFromTigers = tigerList.Select(tiger => ConvertToCat(tiger)).ToList();` – Rufus L Jul 31 '18 at 18:43
  • @RufusL I like the idea! and one can shorten it further with `tigerList.Select(ConvertToCat).ToList();` – Ousmane D. Jul 31 '18 at 18:45
  • Can you have a select inside a select? For example, if another property of cat needs to be converted. For example if owner was a list of owners needs to be converted from another list still: OwnerList = tiger.Ownerlist.Select(owner => new HouseOwner(){ NewOwner = owner + "new" }).ToList() – Watson Jul 31 '18 at 18:50

1 Answers1

10

You can use the Select clause along with ToList():

var tigers_to_cats_approximation =
    tigerlist
        .Select(tiger => new Cat()
        {
            Tail = tiger.Tail / 2,
            Teeth = tiger.Teeth / 3,
            HousePet = true,
            Owner = new Owner() { name = "Tim" }
        })
        .ToList();
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126