1

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>();
}

If I wanted to return new of model2, how would I do that?

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

I get an error - Invalid expression [ after Model1Items

1
  • 1
    Reading a book or documentation about basic c# syntax would be more useful than asking it here. Commented Jul 11, 2018 at 23:27

3 Answers 3

1

C# is not as concise as javascript. So, given your code this is how you would do it:

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...
    }
};

For documentation on initializers, see the docs at microsoft here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers

Sign up to request clarification or add additional context in comments.

Comments

0

Your answer looks very JavaScript-y, but you have it tagged "C#". It's This is how you'd do it:

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

Comments

0

Try

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

1 Comment

Copied from the initial post (before the Josh changed it)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.