Wat*_*son 6 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" }
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在做一些XML apis,进入的请求对象类似于需要出去的响应对象.如果可能,上述将是非常方便的; 比auto-mapper要多得多.
您可以使用该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();
Run Code Online (Sandbox Code Playgroud)