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
@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.
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.
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());
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With