Sithija Sahan
Sithija Sahan

Reputation: 57

How to group in linq list and concatenate some string in c# linq

I have a domain entity called "HoldItems" and i created a list of HoldItems object.

All the attribute on that HoldItems are:

public int TransactionNo;
public int TransactionID;
public int ItemNo;
public String ItemName;
public int Qty;
public double Price;
public double TotalPrice;
public double DiscountPrice;
public int ItemType;
public bool VatInclude;
public double VatPrice;
public string Note;
public List<HoldExtraMenu> ExtraMenuList;
public string BelongCategoryName;
public int BelongItemNo;
public int BelongItemIndex;
public int BelongCategoryID;

I wrote some LINQ query like this, that selectedItemList represent List<DomainEntities.HoldItems>

var results = from myobject in selectedItemList
              where myobject.ItemType == 5
              where myobject.BelongItemIndex==selectedItemList.IndexOf(C)                                      
              orderby myobject.BelongCategoryName                                                                            
              select myobject;

Now the question is, I need to group this result by BelongCategoryName and concatenate output column for ItemName using add ","

Upvotes: 2

Views: 1888

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56489

You can achieve the requirement as follows:

var resultSet = 
       results.GroupBy(e => e.BelongCategoryName)
              .ToDictionary(e => e.Key, 
                  g => string.Join(",", g.Select(a => a.ItemName)));

resultSet is now a Dictionary<string, string>.

or if you want to chain the above query to the one you've already started:

var results = (from myobject in selectedItemList
               where myobject.ItemType == 5
               where myobject.BelongItemIndex == selectedItemList.IndexOf(C)
               orderby myobject.BelongCategoryName
               group myobject by myobject.BelongCategoryName)
               .ToDictionary(e => e.Key,
                      g => string.Join(",", g.Select(a => a.ItemName)));

or using query syntax only:

var results = from myobject in selectedItemList
              where myobject.ItemType == 5
              where myobject.BelongItemIndex == selectedItemList.IndexOf(C)
              orderby myobject.BelongCategoryName
              group myobject by myobject.BelongCategoryName into h
              select new
              {
                   BelongCategoryName = h.Key,
                   ItemNames = string.Join(", ", from e in h select e.ItemName)
              };

Upvotes: 3

Related Questions