Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatinating properties in a list of items

Tags:

c#

.net

loops

linq

I am having trouble with a small section of code.

I have a List of a MapItem class with a couple properties, Address and Html, and I need to concatenate the Html properties for each item with an identical Address property For example:

firstMapItem = new MapItem { Address = "1122 Elm Street", 
                             Html="<p>some html</p>" };  
secondMapItem = new MapItem { Address = "1122 Elm Street", 
                              Html="<p>different html</p>" };

would become:

firstMapItem.Address == "1122 Elm Street";
firstMapItem.Html == "<p>some html</p><p>different html</p>";

secondMapItem.Address == "1122 Elm Street"; 
secondMapItem.Html == "<p>some html</p><p>different html</p>";

This is what I have tried so far:

            foreach (MapItem item in mapItems)
            {
                var sameAddress = from m in mapItems
                                  where m.Address == item.Address
                                  select m;

                if (sameAddress.Count() > 1)
                {
                    //tried inserting -> item.Html = ""; right here as well
                    foreach (MapItem single in sameAddress)
                    {
                        item.Html += single.Html;
                    }
                }
            }

I am probably making this more complicated than it needs to be.

Thanks in advance.

like image 568
Bryan Weaver Avatar asked Dec 28 '22 22:12

Bryan Weaver


2 Answers

You could group by Address and then concatenate the Html values:

var results = from m in mapItems
              group m by m.Address into ms
              select new MapItem
              {
                  Address = ms.Key,
                  Html = string.Concat(ms.Select(m => m.Html))
              };
like image 194
Will Vousden Avatar answered Dec 30 '22 11:12

Will Vousden


Use a grouping on the address, then just string.Join the Html of all the items in the group to produce a new MapItem:

var resultList = mapItems.GroupBy(m => m.Address)
                         .Select(g => new MapItem() { Address = g.Key, Html = string.Join("", g.Select(x => x.Html)) })
                         .ToList();

Edit:

Like the other solutions presented so far above approach will remove duplicates - that doesn't seem to be what you want - below a solution that creates a list that is not deduplicated (so will produce 2 items for the sample input)

var resultList = mapItems.GroupBy(m => m.Address)
                         .Select(g => g.Select( item => new MapItem() { Address = g.Key, Html = string.Join("", g.Select(x => x.Html)) } ))
                         .SelectMany( x=> x)
                         .ToList();
like image 45
BrokenGlass Avatar answered Dec 30 '22 12:12

BrokenGlass