开发者

Binding nested lists using Lambda (C#)

开发者 https://www.devze.com 2023-04-07 06:24 出处:网络
I have this piece of code that I\'m trying to convert to lambda - foreach (var facet in response.Result.Facets)

I have this piece of code that I'm trying to convert to 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);
            }

Here's what I have so far -

response.Result.Facets.ForEach(x => searchModel.Facets.Add(new Facet
                                                                               {
                                                                                   Parent = x.Title,
                                                                                   Items = ???//x.Subelements.ForEach(y=>)
                                  开发者_如何学Python                                             }));

And the classes -

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

How do I bind List<SearchElement> to List<Items> by mapping each element (title = y.Title..) all in one line within a lambda expression? Is it possible?


Try something like this:

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
            }),
    });

EDIT: Lambda version per request in comment.

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
                    })),
        }));

Much the same as with LINQ. Is this what you were after?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号