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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/991017/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:03:43  来源:igfitidea点击:

How to add to a list using Linq's aggregate function C#

c#linqaggregate

提问by Slaggg

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.

我有一组我想转换为不同类型的一种类型的对象。这可以用 foreach 轻松完成,但我想弄清楚如何使用 Linq 的聚合函数来做到这一点。

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.

问题是所有聚合示例都使用类型 line string 或 int,它们支持“+”运算符。我希望累加器类型是一个列表,它不支持“+”语义。

Here's a quick example:

这是一个快速示例:

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)) );

The problem is that List<>.Add returns void. The return type of the second parameter to Aggregate needs to be a List.

问题是 List<>.Add 返回 void。Aggregate 的第二个参数的返回类型需要是一个列表。

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.

但是我找不到任何支持这种东西的集合类型。

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!

似乎这在 Linq 中应该很容易实现。有办法吗?另外,如果我错过了一种更简单的方法,我也很想了解它。谢谢!

采纳答案by Samuel Hyman

I think a call to Selectcombined with ToList()might be what you need here. For example:

我认为调用Select结合ToList()可能是您在这里需要的。例如:

context.Items
  .Select(item => new DestinationType(item.A, item.B, item.C))
  .ToList();

回答by Dustin Campbell

Assuming this is LINQ to Objects, try...

假设这是 LINQ to Objects,请尝试...

var newSet = set.Aggregate(new List<DestinationType>(),
                                    (list, item) =>
                                    {
                                        list.Add(new DestinationType(item.A, item.B, item.C));
                                        return list;
                                    });

回答by Dario

You can just apply selecthere.

你可以在select这里申请。

var newSet = set.Select(item => new DestinationType(...)).ToList();

Aggregate(generally known as foldor reduce) is used to combineelements together where selectapplies a function to each element.

Aggregate(通常称为foldreduce)用于元素组合在一起,其中select将函数应用于每个元素。

Ex:

前任:

Let fbe a unary function, then [a, b, c].select(f)equals [f(a), f(b), f(c)].

f是一个一元函数,则 等于。[a, b, c].select(f)[f(a), f(b), f(c)]

Let fbe a binary function, then [a, b, c].aggregate(f, init)equals f(a, f(b, f(c, init))).

f是一个二元函数,则等于。[a, b, c].aggregate(f, init)f(a, f(b, f(c, init)))

The way you chose in your example is uncommon in C# but often used in functional programming where (linked) lists are transformed into new lists instead of changing an existing collection:

您在示例中选择的方式在 C# 中并不常见,但经常用于函数式编程,其中(链接)列表被转换为新列表而不是更改现有集合:

reversed = fold (\list element -> element:list) [] [1..10]

If you really want to do this computation with aggregate, use Dustin's solution or better implement a linked-list-based type for immutable collections (you can even give this type an operator +).

如果你真的想用 来做这个计算aggregate,使用 Dustin 的解决方案或者更好地为不可变集合实现一个基于链表的类型(你甚至可以给这个类型一个operator +)。

回答by Talljoe

list.AddRange(context.Items.Select(item => 
  new DestinationType(item.A, item.B, item.C));

I realize it doesn't use the Aggregate function, but you should probably find a better example to use to learn the aggregate.

我意识到它不使用聚合函数,但您可能应该找到一个更好的示例来学习聚合。

回答by Aidamina

Unless I'm missing something obvious, why not just do:

除非我遗漏了一些明显的东西,否则为什么不这样做:

public class DestinationType
{
    public DestinationType(int A, int B, int C) { ... }
}

var newSet = from item in context.Items
    select new DestinationType(item.A, item.B, item.C);