如何在C#中组合TimeSpan和String类型的两个列表



如果我有两个这样的列表:

public static List<TimeSpan> times = new List<TimeSpan>();
public static List<string> names = new List<string>();

如何将它们组合以获得等输出

["Bob",00:00:02:003,"Emily",00:00:4:543]

名称和时间按正确顺序显示在哪里?

您可以使用Enumerable.Zip:

string[] result = times.Zip(names, (t, n) => $"{n}, {t:hh\:mm\:ss}").ToArray();

您也可以简单地提供一个方法并更改返回类型:

var result = times.Zip(names, FormatTimeAndName).ToArray();

// string is just an example since i don't know what you really need, maybe a json
private static string FormatTimeAndName(TimeSpan time, string name)
{
return $"{name}, {time:hh\:mm\:ss}";
}

可以将它们组合成List<object>,如下所示:

public static List<TimeSpan> times = new List<TimeSpan>()
{
new TimeSpan(0, 0, 0, 2, 3), new TimeSpan(0, 0, 0, 4, 543)
};
public static List<string> names = new List<string>()
{
"Bob", "Emily"
};
var listOfObj = names.Cast<object>().Zip(times.Cast<object>()).ToList();

但是,建议您为数据提供更多的结构。元组在这里是一个可靠的选择:

public static List<TimeSpan> times = new List<TimeSpan>()
{
new TimeSpan(0, 0, 0, 2, 3), new TimeSpan(0, 0, 0, 4, 543)
};
public static List<string> names = new List<string>()
{
"Bob", "Emily"
};
var listOfTuple = names.Select((n, i) => (Name: n, Time: times[i])).ToList();

简单地交错不匹配类型的列表并不是一个好策略。

最新更新