本文介绍了Linq加入 - 有更好的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我必须解析一个日期字符串。年,月和日都可以采用各种格式(年份为yy或yyyy)。



要获得一系列有效格式,我有每个日期 - 部分在一个单独的数组中。我使用Join(此Enumerable源)linq扩展将所有这些连接在一起。代码如下:



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:

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





我相信你能看到我不知道的一点喜欢。加入表1 = 1,bleh!



我更喜欢扩展语法到linq语法,所以我不会使用它,但它的受欢迎程度使谷歌搜索全部更难。



所以:我应该如何加入这些阵列?



谢谢^ _ ^

Andy



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

推荐答案

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:

var query = from y in years
            from m in months
            from d in days
            select y + "/" + m + "/" + d;

return query.ToArray();


这篇关于Linq加入 - 有更好的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 04:00