Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq select to new object

Tags:

c#

linq

group-by

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

like image 589
Jeff Avatar asked May 25 '12 07:05

Jeff


People also ask

What is select new LINQ?

@CYB: select new is used when you want your query to create new instances of a certain class, instead of simply taking source items. It allows you to create instances of a completely different class, or even an anonymous class like in OP's case.

How do I select a query in LINQ?

LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You can select the whole object as it is or only some properties of it. In the above example, we selected the each resulted string elements.


2 Answers

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

forsingle object make use of stringbuilder and append it that will do or convert this in 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());    
like image 172
Pranay Rana Avatar answered Sep 21 '22 16:09

Pranay Rana


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(); 
like image 43
dckuehn Avatar answered Sep 17 '22 16:09

dckuehn