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
Solution 1:
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());
Solution 2:
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();