문제

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