gpt4 book ai didi

c# - 用于在 C# 中追加集合的 StringBuilder 扩展方法

转载 作者:太空狗 更新时间:2023-10-29 22:03:31 27 4
gpt4 key购买 nike

在 C# 中,我正在尝试为 StringBuilder 构建一个名为 AppendCollection() 的扩展方法,它可以让我这样做:

var sb1 = new StringBuilder();
var sb2 = new StringBuilder();
var people = new List<Person>() { ...init people here... };
var orders = new List<Orders>() { ...init orders here... };

sb1.AppendCollection(people, p => p.ToString());
sb2.AppendCollection(orders, o => o.ToString());

string stringPeople = sb1.ToString();
string stringOrders = sb2.ToString();

stringPeople 最终会为列表中的每个人添加一行。每行都是 p.ToString() 的结果。同样对于 stringOrders。我不太确定如何编写代码以使 lambda 与泛型一起工作。

最佳答案

使用 Func<T,string>代表。

public static void AppendCollection<T>(this StringBuilder sb, 
IEnumerable<T> collection, Func<T, string> method) {
foreach(T x in collection)
sb.AppendLine(method(x));
}

关于c# - 用于在 C# 中追加集合的 StringBuilder 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/353842/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com