开发者

Storing dates, which structure? c#

Say I ha开发者_JAVA百科ve a list of 1000 random dates, call it L

I dont think c# has a 'Tree' collection, so Im wondering how to implement the following:

The tree will be 3 stages deep, the first stage contains the year, the next stage contains all months in L in the parent year, and the final stage contains all days in the 'parent' month, and 'grandparent' year.

What sort of collection should I use, or I could just use a nested array?


I've not tested the code, but you should be able to do something like this:

class Container
{
    public Container() { Items = new Dictionary<int, Container>(); }
    public DateTime DateTime {get;set;}
    Dictionary<int, Container> Items {get;set;}
}

Dictionary<int, Container> items = new Dictionary<int, Container>();

foreach (var date in theListCalledL)
{
    Container yearContainer;
    if (!items.TryGetValue(date.Year, out yearContainer))
    {
        yearContainer = new Contanier{DateTime = date};
        items.Add(date.Year, yearContainer);
    }

    Container monthContainer;
    if (!yearContainer.Items.TryGetValue(date.Month, out monthContainer))
    {
        monthContainer = new Contanier{DateTime = date};
        yearContainer.Add(date.Month, monthContainer);
    }

    Container dayContainer;
    if (!monthContainer.Items.TryGetValue(date.Day, out dayContainer))
    {
        dayContainer = new Contanier{DateTime = date};
        monthContainer.Add(date.Day, dayContainer);
    }
}

//and to get items:
var container = items[1997][8][10];
Console.WriteLine("The date was: " + contanier.DateTime);

var tmp = items[1997];
Console.WriteLine("1997 has items for " + tmp.Items.Count + " months.");


How about

Dictionary<int, Dictionary<int, HashSet<int>>> dateTree;

But really, with out knowing how you need to use it, we can't reall help. Can you give us more information on why you want to store dates this way?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜