我有一个linq查询
var x = (from t in types select t).GroupBy(g =>g.Type)
按类型对对象进行分组,因此我想要包含所有分组对象及其计数的单个新对象。像这样:
type1, 30
type2, 43
type3, 72
更清楚:分组结果应该在一个对象中,而不是每个项目类型的对象
答案 0 :(得分:33)
阅读:来自Microsoft MSDN网站的101 LINQ Samples中的LINQ - Grouping Operators
var x = from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };
forsingle对象使用stringbuilder并附加它将以字典的形式执行或转换它
// 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());
答案 1 :(得分:26)
所有分组的对象或所有类型?听起来你可能只是想要:
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());
无需选择成对和然后构建字典。
答案 2 :(得分:24)
这里的答案让我很接近,但在2016年,我能够编写以下LINQ:
List<ObjectType> objectList = similarTypeList.Select(o =>
new ObjectType
{
PropertyOne = o.PropertyOne,
PropertyTwo = o.PropertyTwo,
PropertyThree = o.PropertyThree
}).ToList();
答案 3 :(得分:3)
var x = from t in types
group t by t.Type into grouped
select new { type = grouped.Key,
count = grouped.Count() };
答案 4 :(得分:1)
如果您希望能够对每种类型执行查找以获得其频率,则需要将枚举转换为字典。
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)]);
答案 5 :(得分:0)
这是一篇很棒的文章,介绍了从LINQ查询创建新对象所需的语法。
但是,如果用于填充对象字段的赋值不仅仅是简单赋值,例如,将字符串解析为整数,并且其中一个失败,则无法对其进行调试。您无法在任何单个分配上创建断点。
如果将所有赋值移动到子例程,并从那里返回一个新对象,并尝试在该例程中设置断点,则可以在该例程中设置断点,但断点永远不会被触发。 / p>
所以而不是:
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<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);
}
这使我能够轻松调试并确定哪个分配失败。在这种情况下,XElement缺少我在SuggestionItem中设置解析的字段。
我在为新的库例程编写单元测试的同时,使用Visual Studio 2017遇到了这些问题。