C#集合初始化器foreach

时间:2018-07-31 18:26:16

标签: c# collection-initializer

在c#中是否可以执行类似于以下内容的操作?

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" }
           }
     }
}

我正在做一些XML api,传入的请求对象类似于需要发出的响应对象。如果可能的话,上面的方法将非常方便。比自动映射器要重要得多。

1 个答案:

答案 0 :(得分:8)

您可以将Select子句与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();