[英]how to yield an anonymous class in IEnumerable.GroupBy<T> “on the fly” (without enumerating result) in C# LINQ?
I do like this now (thanks to StackOverflow): 我现在喜欢这个(感谢StackOverflow):
IEnumerable<object> Get()
{
var groups = _myDatas.GroupBy(
data => new { Type = data.GetType(), Id = data.ClassId, Value = data.Value },
(key, rows) => new
{
ClassId = key.Id,
TypeOfObject = key.Type,
Value = key.Value,
Count = rows.Count()
}));
foreach (var item in groups)
{
yield return item;
}
}
IEnumerable<MyData> _myDatas;
But is possible to make faster or more "elegant" by not having last foreach loop, but yielding it when the group/anonymous class instance is created? 但是,如果没有上一个foreach循环,而是在创建组/匿名类实例时产生它,是否可以使速度更快或更优雅?
I would guess fastest way would be to write it open and: 我想最快的方法是将其写为开放并:
But I'm trying to learn some LINQ (and C# features in general) so I don't want to do that. 但是我想学习一些LINQ(以及一般的C#功能),所以我不想这样做。
The rest of example is here: 其余示例在这里:
public abstract class MyData
{
public int ClassId;
public string Value;
//...
}
public class MyAction : MyData
{
//...
}
public class MyObservation : MyData
{
//...
}
You should be able to return groups
directly, though you might need to change your return type from IEnumerable<Object>
to just IEnumerable
. 你应该能够返回groups
直接,虽然你可能需要从改变你的返回类型IEnumerable<Object>
只是IEnumerable
。
So: 所以:
IEnumerable Get()
{
var groups = _myDatas.GroupBy(
// Key selector
data => new {
Type = data.GetType(),
Id = data.ClassId,
Value = data.Value
},
// Element projector
(key, rows) => new
{
ClassId = key.Id,
TypeOfObject = key.Type,
Value = key.Value,
Count = rows.Count()
}
);
return groups;
}
groups
has the type IEnumerable< IGrouping< TKey = Anonymous1, TElement = Anonymous2 > >
, so you can return it directly. groups
具有IEnumerable< IGrouping< TKey = Anonymous1, TElement = Anonymous2 > >
,因此您可以直接将其返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.