Can't use converter on list of tuples

Viewed 76

First of all, my code references System.ValueTuple.

I have a list of tuples:

List<(string, string)> theme

and I would like to convert the first string of the tuple to a DateTime in one sweep, so I am trying to create a Converter to use with List.ConvertAll. This doesn't give error:

var conv = new Converter<string,DateTime>(x => DateTime.ParseExact(x, "yyyy-MM-dd", null));

but clearly it's not what I need. When I try to simply use tuples as input/output for the lambda I get an error:

(Delegate 'Converter)<(string,string),(DateTime,string)>' does not take two arguments)

var conv = new Converter<(string,string),(DateTime,string)>
           ( (x,y) => (DateTime.ParseExact(x, "yyyy-MM-dd", null),y) );

But I'm not passing two arguments. Or am I??? Thanks for your help.

2 Answers

I think this should work ?

var conv = new Converter<(string, string), (DateTime, string)>(x => (DateTime.ParseExact(x.Item1, "yyyy-MM-dd", null), x.Item2));

Your second attempt is very close. In the following statement, (x,y) implies that two arguments will be passed:

new Converter<(string,string),(DateTime,string)>((x,y) => (DateTime.ParseExact(x, "yyyy-MM-dd", null),y));

However the Tuple it will receive is a single argument, and as such the statement should be:

new Converter<(string,string),(DateTime,string)>(x => (DateTime.ParseExact(x.Item1, "yyyy-MM-dd", null),x.Item2));
Related