C# 如何在Linq中对字符串进行求和格式设置?
我有数组字符串格式(hh.mm) 多少钱? 我使用扩展名:C# 如何在Linq中对字符串进行求和格式设置?,c#,linq,C#,Linq,我有数组字符串格式(hh.mm) 多少钱? 我使用扩展名: static class SumExtensions { public static String Sum<T>(this IEnumerable<T> source, Func<T, String> selector) { return source.Select(selector).Aggregate((x, y) => x + y); } } 静态
static class SumExtensions
{
public static String Sum<T>(this IEnumerable<T> source, Func<T, String> selector)
{
return source.Select(selector).Aggregate((x, y) => x + y);
}
}
静态类扩展
{
公共静态字符串和(此IEnumerable源,Func选择器)
{
返回源。选择(选择器)。聚合((x,y)=>x+y);
}
}
但是我不明白解析字符串和求和的位置,您应该首先将数据结构从字符串更改为
然后,您可以简单地使用函数对数组中的值求和 首先,您需要将
字符串
转换为时间跨度
表示。
这是必要的,因为TimeSpan
表示允许对时间间隔执行算术运算
string[] timeSpanStrings = new[]
{
"01.00", "02.00"
};
var timeSpans = timeSpanStrings.Select(t => TimeSpan.ParseExact(t, @"hh\.mm", CultureInfo.InvariantCulture));
var sumTimeSpan = timeSpans.Aggregate((t1, t2) => t1.Add(t2));
变量
sumTimeSpan
包含结果。求和是什么意思?你的意思是将“12.12”、“11.11”连接成“12.12,11.11”?还是说“和”你的意思是“01.00”+“01.00”=“02.00”(如TimeSpan
s)?对象应该表示适当的结构。因此,与其使用hh:mm格式的数据,不如创建一个wrapper,tha将及时解析该数据。或分钟数。或“总和”的意思是“01.00”+“01.00”=“02.00”-是的。但这是如何在linq中创建的?是的,我需要在linq@simply丹尼斯,你的问题已经有了适当的范围。唯一的问题是您必须更改格式,并使用t1.add(t2)代替t1+t2。请阅读有关格式化程序的内容。你的时间跨度转换器真的很差。