我试图这样做....
var entity = landingPages.Select(x = new MyClass { name = x.name, age = x.age });
唯一的问题是,年龄实际上是一个集合,所以我想我会这样做......
var entity = landingPages.Select(x = new MyClass { name = x.name, age.add(x.age) });
但它不起作用。这可能吗?
答案 0 :(得分:2)
var entity = landingPages.Select(x => new MyClass
{ //this is an initialization block. Only Property Assignment is allowed.
name = x.name,
age.add(x.age) //arbitrary statements are not allowed in initialization blocks.
});
您没有说明哪个年龄是一个集合(LandingPage的年龄或MyClass的年龄)。
如果是LandingPage的年龄,则:将单个值转换为集合。
IEnumerable<MyClass> query = landingPages.Select(x => new MyClass
{
name = x.name,
age = new List<int>() { x.age } //this is a collection initializer
});
如果是MyClass的年龄,那么:将集合转换为单个值。
IEnumerable<MyClass> query = landingPages.Select(x => new MyClass
{
name = x.name,
age = x.age.Sum()
});