我收集了一种类型的对象,希望将其转换为另一种类型.使用foreach可以很容易地做到这一点,但是我想弄清楚如何使用Linq的聚合函数来做到这一点.
I have a collection of objects of one type that I'd like to convert to a different type. This can be done easily with foreach, but I'd like to figure out how to use Linq's aggregate function to do it.
问题是所有聚合"示例都使用类型为"string"或"int"的类型,这些类型均支持"+"运算符.我想将累加器类型设为列表,它不支持'+'语义.
The problem is all the Aggregate examples use types line string or int, which support the '+' operator. I'd like to have the accumulator type be a list, which doesn't support '+' semantics.
这是一个简单的例子:
public class DestinationType { public DestinationType(int A, int B, int C) { ... } } var set = from item in context.Items select new { item.A, item.B, item.C }; var newSet = set.Aggregate( new List<DestinationType>(), (list, item) => list.Add(new DestinationType(item.A, item.B, item.C)) );问题是List<>.Add返回void.第二个参数返回到Aggregate的返回类型必须是一个列表.
The problem is that List<>.Add returns void. The return type of the second parameter to Aggregate needs to be a List.
如果我有一个支持'+'类型语义的列表类型,我可以直接设置第二个参数
If I had a list type that supported '+' type semantics I could just make the second parameter
list + item但是我找不到任何支持这种事情的集合类型.
However I can't find any collection type that supports this kind of thing.
似乎可以在Linq中轻松实现这样的功能.有办法吗?另外,如果我错过了一种更简单的方法,我也想学习一下.谢谢!
Seems like this should be easily possible in Linq. Is there a way? Also, if I'm missing an entirely easier way, I'd love to learn about that too. Thanks!
推荐答案我认为调用选择与 ToList()组合可能就是您所需要的.例如:
I think a call to Select combined with ToList() might be what you need here. For example:
context.Items .Select(item => new DestinationType(item.A, item.B, item.C)) .ToList();更多推荐
如何使用Linq的聚合函数C#添加到列表
发布评论