2011-09-26 100 views
0

我有這一塊,我試圖將轉換爲拉姆達碼 -綁定嵌套列表

foreach (var facet in response.Result.Facets) 
      { 
       var newFacet = new Facet {Parent = facet.Title}; 

       foreach (var element in facet.Subelements) 
       { 
        newFacet.Items.Add(new Facet 
              { 
               Title = element.Title, 
               TotalResults = element.TotalResults 
              }); 
       } 

       searchModel.Facets.Add(newFacet); 
      } 

這裏是我迄今爲止 -

response.Result.Facets.ForEach(x => searchModel.Facets.Add(new Facet 
                       { 
                        Parent = x.Title, 
                        Items = ???//x.Subelements.ForEach(y=>) 
                       })); 

而類 -

public class Facet 
{ 
    public Facet() 
    { 
     Items = new List<Facet>(); 
    } 

    public string Parent { get; set; } 
    public List<Facet> Items { get; set; } 
    public int TotalResults { get; set; } 
    public string Title { get; set; } 
} 



    public class SearchElement 
    { 
     public string Parent { get; set; } 
     public string Title { get; set; } 
     public int TotalResults { get; set; } 
     public IList<ESearchElement> Subelements { get; set; } 
    } 

如何綁定List<SearchElement>List<Items>由每個元件(標題= YT映射itle ..)所有在一個lambda表達式內的行?可能嗎?

回答

0

嘗試這樣:

searchModel.Facets.AddRange(
    from facet in response.Result.Facets 
    select new Facet 
    { 
     Parent = facet.Title, 
     Items = new List<Facet>(
      from element in facet.Subelements 
      select new Facet 
      { 
       Title = element.Title, 
       TotalResults = element.TotalResults 
      }), 
    }); 

編輯:每在評論請求LAMBDA版本。

searchModel.Facets.AddRange(
    response.Result.Facets.Select(
     facet => new Facet 
     { 
      Parent = facet.Title, 
      Items = new List<Facet>(
       facet.Subelements.Select(
        element => new Facet 
        { 
         Title = element.Title, 
         TotalResults = element.TotalResults 
        })), 
     })); 

與LINQ非常相似。這是你以後的事嗎?

+0

謝謝,但這是LINQ。我們可以在Lambda中做同樣的事嗎? – tempid

+0

@ user349308 - 我添加了一個lambda版本。 – Enigmativity