为 .net 中的 var 对象命名

give names to a var object in .net

只是想知道我正在使用网络方法将一些 json 数据 return 发送到网络表单。无论如何,我不希望 json 中的整个 class 只是两列。所以我用 linq 来获取列这里是一个例子。

 IEnumerable<Person> model = new List<Person>
        {
            new Person { id = 1, Name = "Bryan", Phone = "218-0211", Email = "bryan@mail.mil" },
            new Person { id = 2, Name = "Joe", Phone = "248-0241", Email = "joe@mail.mil" },
            new Person { id = 3, Name = "Fred", Phone = "354-0441", Email = "fred@mail.mil" },
            new Person { id = 4, Name = "Mary", Phone = "344-3451", Email = "mary@mail.mil" },
            new Person { id = 5, Name = "Jill", Phone = "127-3451", Email = "jill@mail.mil" }

        };
        var mysubset = from a in model select new { a. Name, a.Email };

不幸的是,当我序列化我的结果并将其发回时,我丢失了列名。所以 data.name 不起作用所以我想知道我可以给 var 类型命名吗?例如,有没有办法做到这一点?

var mysubset = from a in model select new { a. Name, a.Email };
        string myname as string;
        foreach (var item in mysubset)
        {
            myname = subset.Name;
        }

好的,这是实际代码,抱歉,它在 vb 中,但那是我继承的项目

Dim mycollection = From a in cmpnyList select {a.CmpnyName, a.ShipFrom}
return jsSerialize.Serialize(mycollection)

json return 是

[{"Company A","New York"},{"Company B", "Harrisburg"}]

所以我想找回类似

的东西
 [{"CmpnyName":"Company A", "ShipFrom": "New York"},
    {"CmpnyName": "Company B", "ShipFrom": "Harrisburg}]

我相信您正在使用 json.net 使用 jobject(newtonsoft.json.linq)

答案应该是这样的
JObject o = new JObject(
            new JProperty("PersonssList",
            new JArray(
                from p in model
                select new JObject(
                    new JProperty("PersonName", p.Name),
                    new JProperty("Email", p.Email)))));

结果会是这样 json

  {
"PersonssList": [
    {
      "PersonName": "Bryan",
      "Email": "bryan@mail.mil"
    },
    {
      "PersonName": "Joe",
      "Email": "joe@mail.mil"
    },
    {
      "PersonName": "Fred",
      "Email": "fred@mail.mil"
    },
    {
      "PersonName": "Mary",
      "Email": "mary@mail.mil"
    },
    {
      "PersonName": "Jill",
      "Email": "jill@mail.mil"
    }
  ]