By Josh Muroe


2018-07-11 23:23:31 8 Comments

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

3 comments

@C Johnson 2018-07-11 23:32:42

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://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers

@Flydog57 2018-07-11 23:31:22

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

@Afonso 2018-07-11 23:26:29

Try

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

@Afonso 2018-07-11 23:28:49

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

Related Questions

Sponsored Content

39 Answered Questions

[SOLVED] Deep cloning objects

  • 2008-09-17 00:06:27
  • NakedBrunch
  • 691769 View
  • 1864 Score
  • 39 Answer
  • Tags:   c# .net clone

10 Answered Questions

[SOLVED] LINQ: Select an object and change some properties without creating a new object

  • 2009-04-30 16:23:23
  • Rob Volk
  • 186140 View
  • 172 Score
  • 10 Answer
  • Tags:   c# linq

25 Answered Questions

[SOLVED] Why not inherit from List<T>?

44 Answered Questions

[SOLVED] How do I update the GUI from another thread?

19 Answered Questions

[SOLVED] How to Sort a List<T> by a property in the object

7 Answered Questions

[SOLVED] Call one constructor from another

  • 2010-10-24 16:06:31
  • Avi
  • 357308 View
  • 774 Score
  • 7 Answer
  • Tags:   c# constructor

12 Answered Questions

[SOLVED] Get a new object instance from a Type

6 Answered Questions

[SOLVED] Ukkonen's suffix tree algorithm in plain English

16 Answered Questions

[SOLVED] Proper use of 'yield return'

  • 2009-01-03 22:43:35
  • senfo
  • 225266 View
  • 806 Score
  • 16 Answer
  • Tags:   c# yield-return

Sponsored Content