2012-04-18 176 views
2

我有一个Web服务,我打电话来做一个基于电子邮件,名字和姓氏的欺骗检查。我从业务层返回的对象非常大,并且拥有比我需要传回的更多数据。在我的web服务函数中,我只想通过JSON传回10个字段。而不是用这10个字段创建一个新类,我正在寻找循环访问我的大型返回对象,而只是用这10个字段创建一个匿名对象的列表或数组。C#来自循环的匿名对象匿名数组

我知道我可以做匿名对象的匿名数组手动像这样

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"   } 
}; 

我的问题是,我想这样做确切的事情,除了通过我的大对象循环和仅拉出场I需要返回。

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

有什么反对让另一个类? – AakashM 2012-04-18 13:04:33

+0

这不是我的应用程序,我只想使用一次性类,因为它只用于这一个功能,没有其他地方。 – vipergtsrz 2012-04-20 18:47:07

回答

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

如果您使用Linq,则可以使用Take()和Skip()函数进行分页。 – 2012-04-18 13:19:23

+2

@LajosArpad - 确实如此,但我没有看到与问题有关的事情。 – Oded 2012-04-18 13:20:09

+0

我不认为这是我所问的。我想知道如何在循环中创建一个匿名列表。所以我想创建空列表,然后从循环内部添加对象到列表中。 – vipergtsrz 2012-04-24 13:26:30