返回带有另一个对象列表的新对象

时间:2018-07-11 23:23:32

标签: c#

Model1-

    public class model1
    {
       public long Id { get; set; }
       public Guid Unique { get; set; } = Guid.NewGuid();
    }

Model2-

public class model2
{
   public long model2Id { get; set; }
   public List<model1> Model1Items { get; set; } = new List<model1>();
}

如果我想在return new中的model2中使用,怎么办?

return new 
{
   model2Id = 3423432,
   Model1Items = [
      {
        Id = 212,
        Unique = 23432
      }
   ]
}

我遇到错误-Invalid expression [之后的Model1Items

3 个答案:

答案 0 :(得分:1)

C#不如javascript简洁。因此,鉴于您的代码,这就是您的做法:

var m2 = new model2()
{
    model2Id = 3423432,
    Model1Items = new List<model1>()
    {
        new model1() {Id = 212, Unique = new Guid("23432") },
        new model1() {Id = 121, Unique = new Guid("43234") }
        // etc...
    }
};

有关初始化程序的文档,请参阅Microsoft的文档: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers

答案 1 :(得分:0)

尝试

return new model2
{
   Id = 3423432,
   Model1Items = new List<model1>(){
     new model1() 
      {
        Id = 212,
        Unique = 23432
      }
   }
}

答案 2 :(得分:0)

您的答案看起来非常像JavaScript,但是您将其标记为“ C#”。这是您的操作方式:

return new model2
{
    model2Id = 3423432,
    Model1Items = new List<model1>
    {
        new model1
        {
            Id = 212L,
            Unique = Guid.NewGuid()
        }
    }
};