質問

I want to read a Dictionary in C# and possibly get a list or dictionary from it using linq. My problem is that the list can change at any point when I make the request (ie not thread safe i guess).

Can someone give me a example of how I can do this? Would I need to use lock() ?

public Dictionary<DateTime, decimal> GetLatest(DateTime since, Dictionary<DateTime, decimal> requestedDict)
{
    Dictionary<DateTime, decimal> returnList = new Dictionary<DateTime, decimal>();
    returnList = requestedDict.Where(x => x.Key > since).ToDictionary(x => x.Key, x => x.Value);
    return returnList;
}

This is the exception im getting:

Additional information: Collection was modified; enumeration operation may not execute. Thanks

役に立ちましたか?

解決

Use a concurrent dictionary. Locking is implemented for you. And it is thread safe.

他のヒント

You can also implement this as an extension method on IDictionary and then you can pass in whatever dictionary you want concurrent or otherwise

public static class Extensions
{
    public static IDictionary<DateTime, T> GetLatest<T>(this IDictionary<DateTime, T> dict, DateTime since)
    {
        var returnList = new Dictionary<DateTime, T>();
        returnList = dict.Where(x => x.Key > since).ToDictionary(x => x.Key, x => x.Value);
        return returnList;
    }
}

And you use it like this:

dict.GetLatest(new DateTime(2014, 1, 1));
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top