Linq选择新对象

我有一个linq查询

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

它按类型对对象进行分组,因此我想要包含所有分组对象及其计数的单个新对象。 像这样的东西:

 type1, 30 type2, 43 type3, 72 

更清楚:分组结果应该在一个对象中,而不是每个项目类型的对象

阅读: LINQ中的101个LINQ示例 -来自Microsoft MSDN站点的分组操作员

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

forsingle对象使用stringbuilder并附加它将以字典的forms执行或转换它

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

所有分组对象或所有类型 ? 听起来你可能只想要:

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

编辑:如果你在字典中,你可以使用:

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

没有必要选择成对然后构建字典。

这里的答案让我很接近,但在2016年,我能够编写以下LINQ:

 List objectList = similarTypeList.Select(o => new ObjectType { PropertyOne = o.PropertyOne, PropertyTwo = o.PropertyTwo, PropertyThree = o.PropertyThree }).ToList(); 
 var x = from t in types group t by t.Type into grouped select new { type = grouped.Key, count = grouped.Count() }; 

如果您希望能够对每种类型执行查找以获得其频率,那么您将需要将枚举转换为字典。

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

对于从LINQ查询创建新对象所需的语法,这是一篇很棒的文章。

但是,如果用于填充对象字段的赋值不仅仅是简单赋值,例如,将字符串解析为整数,并且其中一个失败,则无法对其进行调试。 您无法在任何单个分配上创建断点。

如果将所有赋值移动到子例程,并从那里返回一个新对象,并尝试在该例程中设置断点,则可以在该例程中设置断点,但永远不会触发断点。

所以代替:

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

要么

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

我做了这个:

 List retList = new List(); var query = from c in doc.Descendants("SuggestionItem") select c; foreach (XElement item in query) { SuggestionItem anItem = new SuggestionItem(item); retList.Add(anItem); } 

这使我能够轻松调试并确定哪个分配失败。 在这种情况下,XElement缺少我在SuggestionItem中设置解析的字段。

我在为新的库例程编写unit testing的同时,使用Visual Studio 2017遇到了这些陷阱。