1

I have a list that contains string and value of that string but list contains multiple string of same name now i want to group name and add value of that name in single entry. for example

Name ..... Value

apple -----  2
mango -----  4
banana ----  8
apple -----  4

Now i want to add apple as a single entry.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Akash Langhani
  • 167
  • 1
  • 10

6 Answers6

1

May be this is what you want:

suppose you have a collection like this:

List<Test> fruits = new List<Test>() {   new Test() { Name="Apple", value=3 }
                                        , new Test() {Name="Apple",value=5 } 
                                        , new Test() {Name="Orange",value=5 }
                                     };

then you can groupBy it and sum similar items like this:

var netFruits= fruits.GroupBy(s => s.Name)
                     .Select(s => new Test() 
                       { 
                           Name=s.Key, 
                           value = s.Sum(b=>b.value) 

                        });

where netFruits will have two entries

  • Apple 8
  • Orage 5

where Test is:

public class Test
{
    public string Name { get; set; }
    public int value { get; set; }
}
Manish Mishra
  • 12,163
  • 5
  • 35
  • 59
  • 1
    The `Where` clause is not needed, just use `value = s.Sum(b=>b.value) ` – sloth Sep 03 '13 at 07:49
  • `s` contains all elements of the group, which are already grouped by `Name`, so all elements in the group satisfy `d.Name==s.Key`. What would be the point of `GroupBy` if it would not group the elements? – sloth Sep 03 '13 at 07:55
  • @DominicKexel, yeah, u are absolutely right :) – Manish Mishra Sep 03 '13 at 07:56
0

You can do groupby like this

yourlist.GroupBy(x=>x.YourField())
Ehsan
  • 31,833
  • 6
  • 56
  • 65
0

So they are separated with "-----"?

var groups = list.Select(str => str.Split(new[]{"-----"}, StringSplitOptions.None))
    .Select(split => new { Name = split.First(), Value = split.Last() })
    .GroupBy(x => x.Name);

foreach (var grp in groups)
{
    Console.WriteLine("Name:{0} Values:{1}", grp.Key, string.Join(",", grp.Select(x => x.Value)));
}

However, it is not clear what you mean with "Now i want to add apple as a single entry".

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

If I think I know what you want is retreiving distint values. Than this is how it can be do

        List<String> MyListOfFruit = new List<String>()
        {
            {"Banana"},
            {"Banana"},
            {"Apple"}
        };
        List<String> GroupedListOfFruits = new List<String>();
        GroupedListOfFruits.AddRange(MyListOfFruit.Distinct());
        //Now GroupedListOfFruits contains two items: Banana and Apple.

Otherwise post a piece of your code with what kind of list you exactly have. Do you have list of KeyValuePair<String, int> maybe?

Mike de Klerk
  • 11,906
  • 8
  • 54
  • 76
0

Since the number of - separating the value from the key seems to be variable, I guess using a Regex to split is more appropriate:

var query = yourlist.Select(x=>{
         var arr = Regex.Split(x,@"[-]+");
         return new{
            Name = arr[0],
            Value = Int32.Parse(arr[1])
         };
    })
    .GroupBy(x=>x.Name)
    .Select(x=> new{Name = x.Key, Value=x.Sum(y=>y.Value)});

In this way you'll have a new anonymous object, with property Name equal to your string, and property Value equal to the sum of the Values of the elements with such Name.

If, instead you want as a return a string with the sum of the values as value, you can replace the last select with:

     .Select(x=> x.Key + " ----- " + x.Sum(y=>y.Value).ToString());

And if, you already have a list with a name and value field, just remove the first Select.

Save
  • 11,450
  • 1
  • 18
  • 23
0
list.Distinct(); 

make sure you have included System.Linq in yr namespace.

Rauld
  • 980
  • 2
  • 10
  • 19