我看过这个简单的例子.净聚合函数的工作原理如下:

string[] words = { "one", "two", "three" };
var res = words.Aggregate((current, next) => current + ", " + next);
Console.WriteLine(res);

如果您希望聚合更复杂的类型,如何使用"Aggregate"函数呢? 例如:一个具有两个属性(如‘key’和‘value’)的类,并且您希望输出如下所示:

"MyAge: 33, MyHeight: 1.75, MyWeight:90"

推荐答案

您有两个 Select :

  1. 投影到string,然后聚合:

    var values = new[] {
        new { Key = "MyAge", Value = 33.0 },
        new { Key = "MyHeight", Value = 1.75 },
        new { Key = "MyWeight", Value = 90.0 }
    };
    var res1 = values.Select(x => string.Format("{0}:{1}", x.Key, x.Value))
                    .Aggregate((current, next) => current + ", " + next);
    Console.WriteLine(res1);
    

    这样做的优点是使用前string个元素作为种子(没有前缀","),但会为进程中创建的字符串消耗更多内存.

  2. 使用接受种子的聚合重载,可能是StringBuilder:

    var res2 = values.Aggregate(new StringBuilder(),
        (current, next) => current.AppendFormat(", {0}:{1}", next.Key, next.Value),
        sb => sb.Length > 2 ? sb.Remove(0, 2).ToString() : "");
    Console.WriteLine(res2);
    

    第二个委托使用条件修剪开始的",",将我们的StringBuilder转换为string,.

Asp.net相关问答推荐

如何删除字符串的定义部分?

登录成功后 User.Identity.IsAuthenticated 为 false

在构建时自动停止/重新启动 ASP.NET 开发服务器

有没有办法在外部 javascript 文件中使用<%= someObject.ClientID %>?

如何在 ASP.NET core rc2 中禁用浏览器缓存?

正在检索组件的 COM 类工厂......错误:80070005 访问被拒绝. (来自 HRESULT 的异常:0x80070005 (E_ACCESSDENIED))

使用 Elmah 处理 Web 服务中的异常

我可以创建 .config 文件并将其包含到 web.config 中吗?

你如何确定哪个验证器失败了?

Gridview ItemTemplate 中多个判断字段的最佳技术?

通过 jQuery 调用 ASP.NET 服务器端方法

判断邮箱地址是否对 System.Net.Mail.MailAddress 有效

什么是实体框架中的复杂类型以及何时使用它?

无法共同创建探查器错误 - 但未使用探查器

在 Android/Java 和 C# 中计算 SHA256 哈希

这个rendersection的代码是什么意思?

如何验证用户在 CheckBoxList 中 Select 了至少一个复选框?

具有自定义报告创建能力的最佳 ASP.NET 报告引擎

在 ASP.NET 中使用 MasterPages 时使用 JQuery 的正确方法?

如何从 ASP.NET Identity 获取用户列表?