views:

124

answers:

1

I have a Dictionary<string, XMLMessage> where XMLMessage is a struct:

    private struct XMLMessage
    {
        public string Message { get; set; }
        public DateTime TimeRead { get; set; }
    }

I will use the Dictionary similar to this:

storedMessages["1X"] = new XMLMessage() { Message = "<XML>1X</XML>", TimeRead = DateTime.Now };
storedMessages["1Y"] = new XMLMessage() { Message = "<XML>1Y</XML>", TimeRead = DateTime.Now };

There will be a gap in seconds between the the dictionary object assigning a value hence the DateTime object.

At some point I need to keep the keys in the Dictionary but the oldest value to be set to empty.

I have tried this but don't seem to have got it quite right.

storedMessages.Where(x => x.Key.Contains("1")).OrderBy(s => s.Value.TimeRead).Skip(1)

Thanks

UPDATE: I think I can do something like this but wanted to get your opinions

var j = storedMessages.Where(x => x.Key.Contains("1")).OrderByDescending(s => s.Value.TimeRead).First().Key;
storedMessages[j] = new XMLMessage();
+1  A: 

Yes, your updated version looks okay - although I'd say you'd be better off storing a list in time order as well as the dictionary, to make life easier.

I would strongly discourage you from using mutable structs though. Either use a class, or change the struct to be immutable.

Example of making it a class:

private class XmlMessage
{
    public string Message { get; set; }
    public DateTime TimeRead { get; set; }
}

Example of making it an immutable struct:

private struct XmlMessage
{
    private readonly string message;
    private readonly DateTime timeRead;

    public string Message { get { return message; } }
    public DateTime TimeRead { get { return timeRead; } }

    public XmlMessage(string message, DateTime timeRead)
    {
        this.message = message;
        this.timeRead = timeRead;
    }
}

Of course you could make it an immutable class instead...

Jon Skeet
I'm unsure on both counts - could you explain more or provide an example
Jon