51

I have a linq query

var x = (from t in types select t).GroupBy(g =>g.Type)

which groups objects by their type, as a result I want to have single new object containing all of the grouped objects and their count. Something like this:

type1, 30    
type2, 43    
type3, 72

to be more clear: grouping results should be in one object not an object per item type

6 Answers 6

63

The answers here got me close, but in 2016, I was able to write the following LINQ:

List<ObjectType> objectList = similarTypeList.Select(o =>
    new ObjectType
    {
        PropertyOne = o.PropertyOne,
        PropertyTwo = o.PropertyTwo,
        PropertyThree = o.PropertyThree
    }).ToList();
0
50

Read : 101 LINQ Samples in that LINQ - Grouping Operators from Microsoft MSDN site

var x = from t in types  group t by t.Type
         into grp    
         select new { type = grp.key, count = grp.Count() };

For a single object, make use of StringBuilder and append it, or convert this in the form of dictionary:

    // fordictionary 
  var x = (from t in types  group t by t.Type
     into grp    
     select new { type = grp.key, count = grp.Count() })
   .ToDictionary( t => t.type, t => t.count); 

   //for stringbuilder not sure for this 
  var x = from t in types  group t by t.Type
         into grp    
         select new { type = grp.key, count = grp.Count() };
  StringBuilder MyStringBuilder = new StringBuilder();

  foreach (var res in x)
  {
       //: is separator between to object
       MyStringBuilder.Append(result.Type +" , "+ result.Count + " : ");
  }
  Console.WriteLine(MyStringBuilder.ToString());   
0
41

All of the grouped objects, or all of the types? It sounds like you may just want:

var query = types.GroupBy(t => t.Type)
                 .Select(g => new { Type = g.Key, Count = g.Count() });

foreach (var result in query)
{
    Console.WriteLine("{0}, {1}", result.Type, result.Count);
}

EDIT: If you want it in a dictionary, you can just use:

var query = types.GroupBy(t => t.Type)
                 .ToDictionary(g => g.Key, g => g.Count());

There's no need to select into pairs and then build the dictionary.

5
  • Sorry for non clear question. Your solution is very similar to what I need, but I want to have all grouping results in single object, not an object per type
    – Jeff
    May 25, 2012 at 7:34
  • 1
    @Jeff: The answer you've accepted is effectively the same as mine... just in a dictionary. The results are all in a single object (query). It's still not clear what you want to achieve that my solution doesn't do for you. If you're going to group by type, you've got to have one object per group, but here query is the query which will give you all those groups.
    – Jon Skeet
    May 25, 2012 at 7:42
  • Well I know what types I will be looking for in a grouped list, so having it in dictionary seems to be easy enough to create an object outside the query
    – Jeff
    May 25, 2012 at 7:51
  • @Jeff: So you do want a dictionary? (It's still not really clear...) If you want a dictionary, that's fine - see my edit for a slightly simpler way of building that dictionary than the accepted answer.
    – Jon Skeet
    May 25, 2012 at 8:00
  • It is a little different from what I was expecting, but since I can have it it dictionary it is good enough to solve my problem. Thanks a lot for help
    – Jeff
    May 25, 2012 at 8:05
4
var x = from t in types
        group t by t.Type into grouped
        select new { type = grouped.Key,
                     count = grouped.Count() };
2
  • side question: in general, if you do a select new {..} does it insert something in the DB when you updateChanges ? Jun 13, 2013 at 15:58
  • @DanyKhalife you do not need to call updateChanges when you are using select statements. If you use, it will not insert anything, it will just execute a select statement in the DB.
    – daryal
    Jun 17, 2013 at 6:43
1

If you want to be able to perform a lookup on each type to get its frequency then you will need to transform the enumeration into a dictionary.

var types = new[] {typeof(string), typeof(string), typeof(int)};
var x = types
        .GroupBy(type => type)
        .ToDictionary(g => g.Key, g => g.Count());
foreach (var kvp in x) {
    Console.WriteLine("Type {0}, Count {1}", kvp.Key, kvp.Value);
}
Console.WriteLine("string has a count of {0}", x[typeof(string)]);
1

This is a great article for syntax needed to create new objects from a LINQ query.

But, if the assignments to fill in the fields of the object are anything more than simple assignments, for example, parsing strings to integers, and one of them fails, it is not possible to debug this. You can not create a breakpoint on any of the individual assignments.

And if you move all the assignments to a subroutine, and return a new object from there, and attempt to set a breakpoint in that routine, you can set a breakpoint in that routine, but the breakpoint will never be triggered.

So instead of:

var query2 = from c in doc.Descendants("SuggestionItem")
                select new SuggestionItem
                       { Phrase = c.Element("Phrase").Value
                         Blocked = bool.Parse(c.Element("Blocked").Value),
                         SeenCount = int.Parse(c.Element("SeenCount").Value)
                       };

Or

var query2 = from c in doc.Descendants("SuggestionItem")
                         select new SuggestionItem(c);

I instead did this:

List<SuggestionItem> retList = new List<SuggestionItem>();

var query = from c in doc.Descendants("SuggestionItem") select c;

foreach (XElement item in query)
{
    SuggestionItem anItem = new SuggestionItem(item);
    retList.Add(anItem);
}

This allowed me to easily debug and figure out which assignment was failing. In this case, the XElement was missing a field I was parsing for to set in the SuggestionItem.

I ran into these gotchas with Visual Studio 2017 while writing unit tests for a new library routine.

1
  • What is SuggestionItem here ? It's there in your answer but nowhere to be find. Mar 15 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.