我有这段代码,我正在尝试将其转换为lambda -
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; }
}
如何通过将每个元素(title = y.Title ..)全部映射到lambda表达式中的一行来绑定List<SearchElement>
到List<Items>
?有可能吗?
答案 0 :(得分: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大致相同。这就是你追求的目标吗?