Home > other >  How to convert Tuple<object, object> to Tuple<string, DateTime>?
How to convert Tuple<object, object> to Tuple<string, DateTime>?

Time:12-18

I have a List<object> and in this list each object is a Tuple<object, object>. I would like to convert this list to List<Tuple<string, DateTime>> but the following doesnt work:

x = myList.First();
xx = (Tuple<DateTime, string>)x

Error: Unable to cast System.Tuple[obj, obj] to type System.Tuple[DateTime, String]

What can I do?

CodePudding user response:

You are using the old style Tuple classes. C# 7.0 introduced the new (and sexy) ValueTuple types. See also: Tuple types (C# reference). C# supports them with a new syntax for tuple types (e.g. (string, DateTime)) and tuple values (e.g. ("hello", DateTime.Now)).

There is no conversion defined between different types of value tuples. You can convert the whole list like this

var myList = new List<(object, object)> {
    ("hello", DateTime.Now),
    ("world", DateTime.Today)
};
List<(string, DateTime)> typedList = myList
    .Select(t => ((string)t.Item1, (DateTime)t.Item2))
    .ToList();

Or for a single item:

var x = myList.First();
var xx = ((string)x.Item1, (DateTime)x.Item2);

Or in a safe way and with pattern matching

var x = myList.First();
if (x is (string s, DateTime d)) {
    var xx = (s, d);
}
  • Related