2

我有一个我正在调用的网络服务,它根据电子邮件、名字和姓氏进行重复检查。我从业务层返回的对象非常大,并且比我需要传回的数据多得多。在我的网络服务功能中,我只想通过 JSON 传回 10 个字段。我没有用这 10 个字段创建一个新类,而是希望循环遍历我的大型返回对象,然后只创建一个包含这 10 个字段的匿名对象列表或数组。

我知道我可以像这样手动创建一个匿名对象数组

obj.DataSource = new[]
{
    new {  Text = "Silverlight",  Count = 10,  Link = "/Tags/Silverlight"  },
    new {  Text = "IIS 7",        Count = 11,  Link = "http://iis.net"     }, 
    new {  Text = "IE 8",         Count = 12,  Link = "/Tags/IE8"          }, 
    new {  Text = "C#",           Count = 13,  Link = "/Tags/C#"           },
    new {  Text = "Azure",        Count = 13,  Link = "?Tag=Azure"         } 
};

我的问题是我想做那件事,除了循环遍历我的大对象并且只提取我需要返回的字段。

private class DupeReturn
{
    public string FirstName;
    public string LastName;
    public string Phone;
    public string Owner;
    public string Address;
    public string City;
    public string State;
    public string Zip;
    public string LastModified;
}

[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string CheckForDupes(string Email, string FirstName, string LastName)
{
    contact[] list = Services.Contact.GetDupes(Email, FirstName, LastName);
    if (list != null && list.Length > 0)
    {
        List<DupeReturn> dupes = new List<DupeReturn> { };
        foreach (contact i in list)
        {
            DupeReturn currentObj = new DupeReturn
            {
                FirstName = i.firstname,
                LastName = i.lastname,
                Phone = i.telephone1,
                Owner = i.ownerid.ToString(),
                Address = i.address1_line1,
                City = i.address1_city,
                State = i.address1_stateorprovince,
                Zip = i.address1_postalcode,
                LastModified = i.ctca_lastactivityon.ToString()
            };
            dupes.Add(currentObj);
        }
        return Newtonsoft.Json.JsonConvert.SerializeObject(dupes);    
    }
}

如果我不需要的话,我真的不想上额外的私人课程。任何帮助,将不胜感激。

4

1 回答 1

6

使用 LINQ,您可以创建匿名类型的列表。

var dupes = list.Select(i => new { FirstName = i.firstname,
                                   LastName = i.lastname,
                                   Phone = i.telephone1,
                                   Owner = i.ownerid.ToString(),
                                   Address = i.address1_line1,
                                   City = i.address1_city,
                                   State = i.address1_stateorprovince,
                                   Zip = i.address1_postalcode,
                                   LastModified = i.ctca_lastactivityon.ToString()
                                    });
于 2012-04-18T13:05:46.717 回答