[c#] Linq select to new object

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

This question is related to c# linq group-by

The answer is


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

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.


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)]);

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();

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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?

Examples related to group-by

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by Count unique values using pandas groupby Pandas group-by and sum Count unique values with pandas per groups Group dataframe and get sum AND count? Error related to only_full_group_by when executing a query in MySql Pandas sum by groupby, but exclude certain columns Using DISTINCT along with GROUP BY in SQL Server Python Pandas : group by in group by and average? How do I create a new column from the output of pandas groupby().sum()?