来自循环的C#匿名对象数组

时间:2012-04-18 12:58:26

标签: c# anonymous-types

我有一个我正在调用的Web服务,根据email,firstName和lastName进行欺骗检查。我从业务层返回的对象非常大,并且具有比我需要传回的数据更多的数据。在我的Web服务功能中,我只希望通过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);    
    }
}

如果我不需要,我真的不想再增加私人课程。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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()
                                    });