简体   繁体   English

c#collection initializer foreach

[英]c# collection initializer foreach

Is it possible in c# to do something similar to the following? 是否有可能在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" }
           }
     }
}

I'm doing some XML apis and the request objects coming in are similar to the response objects that need to go out. 我正在做一些XML apis,进入的请求对象类似于需要出去的响应对象。 The above would be incredibly convenient if it were possible; 如果可能,上述将是非常方便的; much more so than auto-mapper. 比auto-mapper要多得多。

You can use the Select clause along with ToList() : 您可以将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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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