How can I combine two lists in C# of type TimeSpan and String

Viewed 37

If I have two lists such as this:

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

How can I combine them to get an output such as

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

where the names and times are displayed in correct order?

2 Answers

You can use Enumerable.Zip:

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

You can also simply provide a method and change the return type:

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}";
}

You can combine them into a List<object> like this:

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();

However, you would be well advised to give your data more structure. Tuples is a solid option here:

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();

Simply interleaving lists of mismatched types isn't a great strategy.

Related