如何使用Linq的聚合函数C#添加到列表

编程入门 行业动态 更新时间:2024-10-27 01:35:38
本文介绍了如何使用Linq的聚合函数C#添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我收集了一种类型的对象,希望将其转换为另一种类型.使用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#添加到列表

本文发布于:2023-11-22 09:39:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616920.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   函数   列表   Linq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!