C# Linq 选择新对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10750146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linq select to new object
提问by Jeff
I have a linq query
我有一个 linq 查询
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
更清楚:分组结果应该在一个对象中,而不是每个项目类型的对象
采纳答案by Pranay Rana
Read : 101 LINQ Samplesin that LINQ - Grouping Operatorsfrom Microsoft MSDN site
阅读:101个LINQ样品在LINQ -分组运营商从微软MSDN网站
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
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());
回答by Jon Skeet
All of the grouped objects, or all of the types? It sounds like you may just want:
所有分组的对象,还是所有的类型?听起来您可能只想要:
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);
}
EDIT: If you wantit in a dictionary, you can just use:
编辑:如果你想在字典中使用它,你可以使用:
var query = types.GroupBy(t => t.Type)
.ToDictionary(g => g.Key, g => g.Count());
There's no need to select into pairs and thenbuild the dictionary.
无需成对选择然后构建字典。
回答by daryal
var x = from t in types
group t by t.Type into grouped
select new { type = grouped.Key,
count = grouped.Count() };
回答by Steve
If you want to be able to perform a lookup on each type to get its frequency then you will need to transform the enumeration into a dictionary.
如果您希望能够对每种类型执行查找以获取其频率,那么您需要将枚举转换为字典。
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)]);
回答by dckuehn
The answers here got me close, but in 2016, I was able to write the following LINQ:
这里的答案让我很接近,但在 2016 年,我能够编写以下 LINQ:
List<ObjectType> objectList = similarTypeList.Select(o =>
new ObjectType
{
PropertyOne = o.PropertyOne,
PropertyTwo = o.PropertyTwo,
PropertyThree = o.PropertyThree
}).ToList();
回答by Garnet R. Chaney
This is a great article for syntax needed to create new objects from a LINQ query.
对于从 LINQ 查询创建新对象所需的语法,这是一篇很棒的文章。
But, if the assignments to fill in the fields of the object are anything more than simple assignments, for example, parsing strings to integers, and one of them fails, it is not possible to debug this. You can not create a breakpoint on any of the individual assignments.
但是,如果填充对象字段的赋值不仅仅是简单的赋值,例如,将字符串解析为整数,并且其中一个失败,则无法对此进行调试。您不能在任何单个分配上创建断点。
And if you move all the assignments to a subroutine, and return a new object from there, and attempt to set a breakpoint in that routine, you can set a breakpoint in that routine, but the breakpoint will never be triggered.
如果您将所有赋值移动到子程序,并从那里返回一个新对象,并尝试在该程序中设置断点,您可以在该程序中设置断点,但断点永远不会被触发。
So instead of:
所以而不是:
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)
};
Or
或者
var query2 = from c in doc.Descendants("SuggestionItem")
select new SuggestionItem(c);
I instead did this:
我改为这样做:
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);
}
This allowed me to easily debug and figure out which assignment was failing. In this case, the XElement was missing a field I was parsing for to set in the SuggestionItem.
这使我能够轻松调试并找出失败的分配。在这种情况下,XElement 缺少我正在解析以在 SuggestionItem 中设置的字段。
I ran into these gotchas with Visual Studio 2017 while writing unit tests for a new library routine.
在为新的库例程编写单元测试时,我在 Visual Studio 2017 中遇到了这些问题。

