开发者

Can we initialize an object/collection using LINQ in JSON-like syntax?

开发者 https://www.devze.com 2023-01-22 15:00 出处:网络
Can we do something like this or something similar? var staffs = { \"Staff\": [ { \"ID\" : 1, \"Name\" : \"John\" },

Can we do something like this or something similar?

var staffs = {
               "Staff": 
               [
                { "ID" : 1, "Name" : "John" },
                { "ID" : 2, "Name" : "Mark"}
               ]
            };

foreach (var staff in staffs)
{
    Console.WriteLine("ID: {0}", staff.ID);
    Console.开发者_C百科WriteLine("Name: {0}", staff.Name);
}

Instead of this long code:

public class Test
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
            return;

        List<Staff> staffs = new List<Staff>()
        {
            new Staff() {ID = 1, Name = "John"},
            new Staff() {ID = 2, Name = "Mark"}
        };

        foreach (var staff in staffs)
        {
            Console.WriteLine("ID: {0}", staff.ID);
            Console.WriteLine("Name: {0}", staff.Name);
        }
    }
}

public class Staff
{
    public int ID { get; set; }
    public string Name { get; set; }
}

I tried but Visual Studio shows syntax error.


You can make it shorter but not exactly like JSON.

List<Staff> staffs = new List<Staff>()
{
    new Staff() {ID = 1, Name = "John"},
    new Staff() {ID = 2, Name = "Mark"}
};

...can you turn into: (This is an array not a List<T> but you can wrap it)

var staffs = new[]
{
    new Staff {ID = 1, Name = "John"},
    new Staff {ID = 2, Name = "Mark"}
};


Nope. What you've demonstrated is the allowed syntax for collection and object initializers.

If you're trying to shorten it somewhat you could drop the trailing () off of each initializer, such as:

var list = new List<Staff>
{
    new Staff {ID = 1, Name = "John"},
    new Staff {ID = 2, Name = "Mark"}
}


The closest you can get is:

var staffs = new List<Staff> {
                new Staff{ ID : 1, Name : "John" },
                new Staff{ ID : 2, Name : "Mark"}

            };

foreach (var staff in staffs)
{
    Console.WriteLine("ID: {0}", staff.ID);
    Console.WriteLine("Name: {0}", staff.Name);
}

Note: member names and values are not quoted, but strongly typed (unlike json).

You might be able to deserialize a JSON representation directly to the object graph using a Json serializer.

0

精彩评论

暂无评论...
验证码 换一张
取 消