c# - Linq 在单次迭代中选择和聚合

标签 c# linq aggregate

有没有办法用 linq 做到这一点而不用枚举 fooCollection 两次?

var fooCollection = // get foo
var selectedIds = new List<int>();
var aggregateContent = String.Empty;

foreach (var f in foo)
{
    selectedIds.Add(foo.Id);
    aggregateContent += foo.Content
}

var results = new FooResults
{
    Content = aggregateContent,
    SelectedIds = selectedIds
};

return results;

最佳答案

是的,您可以使用 Enumerable.Aggregate方法:

var result = fooCollection.Aggregate(new FooResult(),
                                    (r,f) => 
                                    { 
                                        r.SelectedIds.Add(f.Id);
                                        r.Content += f.Content;
                                        return r;
                                    });

这样做的好处是没有副作用。我不喜欢 LINQ 中的副作用。 =)

关于c# - Linq 在单次迭代中选择和聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12936501/

相关文章:

c# - 如何关闭网络浏览器控件中的查找窗口

C# 自定义序列化/反序列化以及 DeflateStreams

c# - 将字典分成更小的部分

sql - 使用 LINQ 动态改变 'where' 语句中的条件数

sql - 如何找到以 GB 为单位的列的大小?

c# - 帮助我使用 RegExp 拆分字符串

c# - 加法的十进制顺序影响结果

c# - 使用 LINQ 或 Lambda 从列表中删除实例?

R相当于Excel的 "Sumif(s)"函数跨like列

c# - DataRow[] 聚合函数 C#