1

I want to retrieve common element from list and want to show in below format.

I have a List<Property>, the Property class is as follows:

public class Property 
{
    public Property(){}
    public string Name { get; set; }        
    public string Value { get; set; }
}

Value of list are as below:

Name   Value
---------------
Sam -->  1

Sam -->  2

Sam -->  5

mike --> 2

mike --> 3

Expected result

I wanted to display common items with comma separated values as shown below:

Name       Value
-------------------
Sam  -->  1, 2, 5 

mike -->  2, 3
Theraot
  • 31,890
  • 5
  • 57
  • 86
Sameer
  • 538
  • 1
  • 8
  • 21
  • 2
    If you have tried any code, Do post it . – Suraj Singh Dec 17 '13 at 15:11
  • 1
    Take a look at GroupBy LINQ method. – Pierre-Luc Pineault Dec 17 '13 at 15:11
  • related: [Grouping objects by property value](http://stackoverflow.com/questions/15447648/grouping-objects-by-property-value), [Group By List](http://stackoverflow.com/questions/10141030/group-by-listitem), [Group By Multiple Columns](http://stackoverflow.com/questions/847066/group-by-multiple-columns), [C# List<> GroupBy 2 Values](http://stackoverflow.com/questions/363655/c-sharp-list-groupby-2-values), [C# List - Group By - Without Linq](http://stackoverflow.com/questions/1460309/c-sharp-list-group-by-without-linq) – Theraot Dec 17 '13 at 15:13

1 Answers1

6

A combination of GroupBy and string.Join could do:

List<Property> list = new List<Property>();
var result = list.GroupBy(r => r.Name)
                .Select(r => new 
                        { 
                            Name = r.Key, 
                            Values = string.Join(",", r.Select(t => t.Value)) 
                        });
Habib
  • 219,104
  • 29
  • 407
  • 436