Click here to Skip to main content
15,896,486 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have to parse a date string. the year, month and day can all be in various formats (year in "yy" or "yyyy").

To get an array of valid formats, I have each date-part in a separate array. I join all of these together using the Join(this Enumerable source) linq extension. Code below:

C#
private string[] years = { "yy", "yyy" };
private string[] months = { "M", "MM" };
private string[] days = { "d", "dd" };

string[] formats
{
    get
    {
        return years.Join(
                months,
                y => 1,
                m => 1,
                (y, m) => new {y, m}
            ).Join(
                days,
                n => 1,
                d => 1,
                (n, d) => string.Join("/", n.y, n.m, d)
            ).ToArray();
    }
}


I'm sure you can see the bit I don't like. Joining tables on 1=1, bleh!

I prefer extension syntax to linq syntax, so I won't be using that, but it's popularity makes google searches all the more difficult.

So: How SHOULD I be joining these arrays?

Thanks ^_^
Andy
Posted

1 solution

SelectMany[^] would probably be a better fit:
C#
return years
    .SelectMany(y => months, (y, m) => new { y, m })
    .SelectMany(ym => days, (ym, d) => ym.y + "/" + ym.m + "/" + d })
    .ToArray();

The equivalent query syntax would be:
C#
var query = from y in years
            from m in months
            from d in days
            select y + "/" + m + "/" + d;

return query.ToArray();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900