Search Results

Search found 29 results on 2 pages for 'sorteddictionary'.

Page 1/2 | 1 2  | Next Page >

  • SortedDictionary and SortedList

    - by Simon Cooper
    Apart from Dictionary<TKey, TValue>, there's two other dictionaries in the BCL - SortedDictionary<TKey, TValue> and SortedList<TKey, TValue>. On the face of it, these two classes do the same thing - provide an IDictionary<TKey, TValue> interface where the iterator returns the items sorted by the key. So what's the difference between them, and when should you use one rather than the other? (as in my previous post, I'll assume you have some basic algorithm & datastructure knowledge) SortedDictionary We'll first cover SortedDictionary. This is implemented as a special sort of binary tree called a red-black tree. Essentially, it's a binary tree that uses various constraints on how the nodes of the tree can be arranged to ensure the tree is always roughly balanced (for more gory algorithmical details, see the wikipedia link above). What I'm concerned about in this post is how the .NET SortedDictionary is actually implemented. In .NET 4, behind the scenes, the actual implementation of the tree is delegated to a SortedSet<KeyValuePair<TKey, TValue>>. One example tree might look like this: Each node in the above tree is stored as a separate SortedSet<T>.Node object (remember, in a SortedDictionary, T is instantiated to KeyValuePair<TKey, TValue>): class Node { public bool IsRed; public T Item; public SortedSet<T>.Node Left; public SortedSet<T>.Node Right; } The SortedSet only stores a reference to the root node; all the data in the tree is accessed by traversing the Left and Right node references until you reach the node you're looking for. Each individual node can be physically stored anywhere in memory; what's important is the relationship between the nodes. This is also why there is no constructor to SortedDictionary or SortedSet that takes an integer representing the capacity; there are no internal arrays that need to be created and resized. This may seen trivial, but it's an important distinction between SortedDictionary and SortedList that I'll cover later on. And that's pretty much it; it's a standard red-black tree. Plenty of webpages and datastructure books cover the algorithms behind the tree itself far better than I could. What's interesting is the comparions between SortedDictionary and SortedList, which I'll cover at the end. As a side point, SortedDictionary has existed in the BCL ever since .NET 2. That means that, all through .NET 2, 3, and 3.5, there has been a bona-fide sorted set class in the BCL (called TreeSet). However, it was internal, so it couldn't be used outside System.dll. Only in .NET 4 was this class exposed as SortedSet. SortedList Whereas SortedDictionary didn't use any backing arrays, SortedList does. It is implemented just as the name suggests; two arrays, one containing the keys, and one the values (I've just used random letters for the values): The items in the keys array are always guarenteed to be stored in sorted order, and the value corresponding to each key is stored in the same index as the key in the values array. In this example, the value for key item 5 is 'z', and for key item 8 is 'm'. Whenever an item is inserted or removed from the SortedList, a binary search is run on the keys array to find the correct index, then all the items in the arrays are shifted to accomodate the new or removed item. For example, if the key 3 was removed, a binary search would be run to find the array index the item was at, then everything above that index would be moved down by one: and then if the key/value pair {7, 'f'} was added, a binary search would be run on the keys to find the index to insert the new item, and everything above that index would be moved up to accomodate the new item: If another item was then added, both arrays would be resized (to a length of 10) before the new item was added to the arrays. As you can see, any insertions or removals in the middle of the list require a proportion of the array contents to be moved; an O(n) operation. However, if the insertion or removal is at the end of the array (ie the largest key), then it's only O(log n); the cost of the binary search to determine it does actually need to be added to the end (excluding the occasional O(n) cost of resizing the arrays to fit more items). As a side effect of using backing arrays, SortedList offers IList Keys and Values views that simply use the backing keys or values arrays, as well as various methods utilising the array index of stored items, which SortedDictionary does not (and cannot) offer. The Comparison So, when should you use one and not the other? Well, here's the important differences: Memory usage SortedDictionary and SortedList have got very different memory profiles. SortedDictionary... has a memory overhead of one object instance, a bool, and two references per item. On 64-bit systems, this adds up to ~40 bytes, not including the stored item and the reference to it from the Node object. stores the items in separate objects that can be spread all over the heap. This helps to keep memory fragmentation low, as the individual node objects can be allocated wherever there's a spare 60 bytes. In contrast, SortedList... has no additional overhead per item (only the reference to it in the array entries), however the backing arrays can be significantly larger than you need; every time the arrays are resized they double in size. That means that if you add 513 items to a SortedList, the backing arrays will each have a length of 1024. To conteract this, the TrimExcess method resizes the arrays back down to the actual size needed, or you can simply assign list.Capacity = list.Count. stores its items in a continuous block in memory. If the list stores thousands of items, this can cause significant problems with Large Object Heap memory fragmentation as the array resizes, which SortedDictionary doesn't have. Performance Operations on a SortedDictionary always have O(log n) performance, regardless of where in the collection you're adding or removing items. In contrast, SortedList has O(n) performance when you're altering the middle of the collection. If you're adding or removing from the end (ie the largest item), then performance is O(log n), same as SortedDictionary (in practice, it will likely be slightly faster, due to the array items all being in the same area in memory, also called locality of reference). So, when should you use one and not the other? As always with these sort of things, there are no hard-and-fast rules. But generally, if you: need to access items using their index within the collection are populating the dictionary all at once from sorted data aren't adding or removing keys once it's populated then use a SortedList. But if you: don't know how many items are going to be in the dictionary are populating the dictionary from random, unsorted data are adding & removing items randomly then use a SortedDictionary. The default (again, there's no definite rules on these sort of things!) should be to use SortedDictionary, unless there's a good reason to use SortedList, due to the bad performance of SortedList when altering the middle of the collection.

    Read the article

  • How to use custom IComparer for SortedDictionary?

    - by Magnus Johansson
    I am having difficulties to use my custom IComparer for my SortedDictionary<. The goal is to put email addresses in a specific format ([email protected]) as the key, and sort by last name. When I do something like this: public class Program { public static void Main(string[] args) { SortedDictionary<string, string> list = new SortedDictionary<string, string>(new SortEmailComparer()); list.Add("[email protected]", "value1"); list.Add("[email protected]", "value2"); foreach (KeyValuePair<string, string> kvp in list) { Console.WriteLine(kvp.Key); } Console.ReadLine(); } } public class SortEmailComparer : IComparer<string> { public int Compare(string x, string y) { Regex regex = new Regex("\\b\\w*@\\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled ); string xLastname = regex.Match(x).ToString().Trim('@'); string yLastname = regex.Match(y).ToString().Trim('@'); return xLastname.CompareTo(yLastname); } } I get this ArgumentException: An entry with the same key already exists. when adding the second item. I haven't worked with a custom IComparer for a SortedDictionary before, and I fail to see my error , what am I doing wrong?

    Read the article

  • vb.net using SortedDictionary as combobox datasource

    - by user228058
    I have a combobox which i am binding to a sortedDictionary list, so it displays in ascending order. My question is, I need to display "--Select--" as the first option. Is there any way to either: 1) add another item besides for the datasource or 2) add an unsorted item to the top of the sortedDictionary any other ideas welcome as well :) TIA

    Read the article

  • .NET SortedDictionary But Sorted By Values

    - by Michael Covelli
    I need a data structure that acts like a SortedDictionary<int, double> but is sorted based on the values rather than the keys. I need it to take about 1-2 microseconds to add and remove items when we have about 3000 items in the dictionary. My first thought was simply to switch the keys and values in my code. This very nearly works. I can add and remove elements in about 1.2 microseconds in my testing by doing this. But the keys have to be unique in a SortedDictionary so that means that values in my inverse dictionary would have to be unique. And there are some cases where they may not be. Any ideas of something in the .NET libraries already that would work for me?

    Read the article

  • Unable to read values from Nested SortedDictionary in C#

    - by Yogi
    HI I am using nested SortedDictionary in my code as SortedDictionary<string, SortedDictionary<string, int>> but not able to use value stored in this object. Please find the code which i am using SortedDictionary<string, SortedDictionary<string, int>> baseItemCounts = new SortedDictionary<string, SortedDictionary<string, int>>(); baseItemCounts.Add("1450", new SortedDictionary<string, int>()); baseItemCounts["1450"].Add("1450M", 15); I want to print these values on screen. but don't know how to access it. 1450 1450M ==== 15 Please some one can help?

    Read the article

  • Alternative of SortedDictionary in Silverlight

    - by Rajneesh Verma
    Hi, As we know SortedDictionary is not not present in Silverlightso to find alternative of this i am using Dictionary as System.Collections.Generic . Dictionary (Of TKey, TValue ) . KeyCollection and for sorting i am using LINQ query. see the full code below. Dim sortedLists As New Dictionary(Of String, Object) Dim query = From sortedList In sortedLists Order By sortedList.Key Ascending Select sortedList.Key, sortedList.Value For Each que In query 'get the key value using que.Key 'get the value using...(read more)

    Read the article

  • How do I use Eval() to reference values in a SortedDictionary in an asp Repeater?

    - by MatthewMartin
    I thought I was clever to switch from the memory intensive DataView to SortedDictionary as a memory efficient sortable data structure. Now I have no idea how get the key and value out of the datasource in the <%# or Eval() expressions. SortedDictionary<int, string> data = RetrieveNames(); rCurrentTeam.DataSource = data; rCurrentTeam.DataBind(); <asp:Repeater ID="rNames" runat="server"> <ItemTemplate> <asp:Label ID="lblName" runat="server" Text='<%# Eval("what?") %>' /> </ItemTemplate> </asp:Repeater> Any suggestions?

    Read the article

  • C# .NET: Ascending comparison of a SortedDictionary?

    - by Rosarch
    I'm want a IDictionary<float, foo> that returns the larges values of the key first. private IDictionary<float, foo> layers = new SortedDictionary<float, foo>(new AscendingComparer<float>()); class AscendingComparer<T> : IComparer<T> where T : IComparable<T> { public int Compare(T x, T y) { return -y.CompareTo(x); } } However, this returns values in order of the smallest first. I feel like I'm making a stupid mistake here. Just to see what would happen, I removed the - sign from the comparator: public int Compare(T x, T y) { return y.CompareTo(x); } But I got the same result. This reinforces my intuition that I'm making a stupid error.

    Read the article

  • C# .NET: Descending comparison of a SortedDictionary?

    - by Rosarch
    I'm want a IDictionary<float, foo> that returns the larges values of the key first. private IDictionary<float, foo> layers = new SortedDictionary<float, foo>(new DescendingComparer<float>()); class DescendingComparer<T> : IComparer<T> where T : IComparable<T> { public int Compare(T x, T y) { return -y.CompareTo(x); } } However, this returns values in order of the smallest first. I feel like I'm making a stupid mistake here. Just to see what would happen, I removed the - sign from the comparator: public int Compare(T x, T y) { return y.CompareTo(x); } But I got the same result. This reinforces my intuition that I'm making a stupid error. This is the code that accesses the dictionary: foreach (KeyValuePair<float, foo> kv in sortedLayers) { // ... } UPDATE: This works, but is too slow to call as frequently as I need to call this method: IOrderedEnumerable<KeyValuePair<float, foo>> sortedLayers = layers.OrderByDescending(kv => kv.Key); foreach (KeyValuePair<float, ICollection<IGameObjectController>> kv in sortedLayers) { // ... } UPDATE: I put a break point in the comparator that never gets hit as I add and remove kv pairs from the dictionary. What could this mean?

    Read the article

  • How can I get running totals of integer values from a SortedDictionary?

    - by user578083
    SortedDictionary<int, string> typeDictionary = new SortedDictionary<int, string>(); SortedDictionary<int, int> lengthDictionary = new SortedDictionary<int, int>(); lengthDictionary has values in key value pair as follows: <1,20> <2,8> <3,10> <4,5> i want LINQ query which will return me new list like as follows <1,20> <2,20+8=28> // 20 from key 1 <3,28+10=38> // 28 from key 2 <4,38+5=43> // 38 from key 3 Result should like this: <1,20> <2,28> <3,38> <4,43>

    Read the article

  • LINQ into SortedList

    - by Chris Simmons
    I'm a complete LINQ newbie, so I don't know if my LINQ is incorrect for what I need to do or if my expectations of performance are too high. I've got a SortedList of objects, keyed by int; SortedList as opposed to SortedDictionary because I'll be populating the collection with pre-sorted data. My task is to find either the exact key or, if there is no exact key, the one with the next higher value. If the search is too high for the list (e.g. highest key is 100, but search for 105), return null. // The structure of this class is unimportant. Just using // it as an illustration. public class CX { public int KEY; public DateTime DT; } static CX getItem(int i, SortedList<int, CX> list) { var items = (from kv in list where kv.Key >= i select kv.Key); if (items.Any()) { return list[items.Min()]; } return null; } Given a list of 50,000 records, calling getItem 500 times takes about a second and a half. Calling it 50,000 times takes over 2 minutes. This performance seems very poor. Is my LINQ bad? Am I expecting too much? Should I be rolling my own binary search function?

    Read the article

  • A quick way to map unordered list of longs to buffer location ?

    - by alhazen
    I have a large number of points (indexed by long) that are processed by multiple threads and I'm using a buffer to hold the output results in order. As the number of points processed is huge, what would be an efficient way to map the indexes of the points to the corresponding ordered position in the buffer ? Example: long bufferIndex bufferIndex index (if BufferSize = 2) (if BufferSize = 4) ---------------------------------------------- 2938 0 0 2939 1 1 2941 1 3 2940 0 2 Thanks.

    Read the article

  • Getting an exception when trying to use extension method with SortedDictionary... why?

    - by Polaris878
    I'm trying to place custom objects into a sorted dictionary... I am then trying to use an extension method (Max()) on this sorted dictionary. However, I'm getting the exception: "At least one object must implement IComparable". I don't understand why I'm getting that, as my custom object obviously implements IComparable. Here is my code: public class MyDate : IComparable<MyDate> { int IComparable<MyDate>.CompareTo(MyDate obj) { if (obj != null) { if (this.Value.Ticks < obj.Value.Ticks) { return 1; } else if (this.Value.Ticks == obj.Value.Ticks) { return 0; } else { return -1; } } } public MyDate(DateTime date) { this.Value = date; } public DateTime Value; } class Program { static void Main(string[] args) { SortedDictionary<MyDate, int> sd = new SortedDictionary<MyDate,int>(); sd.Add(new MyDate(new DateTime(1)), 1); sd.Add(new MyDate(new DateTime(2)), 2); Console.WriteLine(sd.Max().Value); // Throws exception!! } } What on earth am I doing wrong???

    Read the article

  • C#/.NET Fundamentals: Choosing the Right Collection Class

    - by James Michael Hare
    The .NET Base Class Library (BCL) has a wide array of collection classes at your disposal which make it easy to manage collections of objects. While it's great to have so many classes available, it can be daunting to choose the right collection to use for any given situation. As hard as it may be, choosing the right collection can be absolutely key to the performance and maintainability of your application! This post will look at breaking down any confusion between each collection and the situations in which they excel. We will be spending most of our time looking at the System.Collections.Generic namespace, which is the recommended set of collections. The Generic Collections: System.Collections.Generic namespace The generic collections were introduced in .NET 2.0 in the System.Collections.Generic namespace. This is the main body of collections you should tend to focus on first, as they will tend to suit 99% of your needs right up front. It is important to note that the generic collections are unsynchronized. This decision was made for performance reasons because depending on how you are using the collections its completely possible that synchronization may not be required or may be needed on a higher level than simple method-level synchronization. Furthermore, concurrent read access (all writes done at beginning and never again) is always safe, but for concurrent mixed access you should either synchronize the collection or use one of the concurrent collections. So let's look at each of the collections in turn and its various pros and cons, at the end we'll summarize with a table to help make it easier to compare and contrast the different collections. The Associative Collection Classes Associative collections store a value in the collection by providing a key that is used to add/remove/lookup the item. Hence, the container associates the value with the key. These collections are most useful when you need to lookup/manipulate a collection using a key value. For example, if you wanted to look up an order in a collection of orders by an order id, you might have an associative collection where they key is the order id and the value is the order. The Dictionary<TKey,TVale> is probably the most used associative container class. The Dictionary<TKey,TValue> is the fastest class for associative lookups/inserts/deletes because it uses a hash table under the covers. Because the keys are hashed, the key type should correctly implement GetHashCode() and Equals() appropriately or you should provide an external IEqualityComparer to the dictionary on construction. The insert/delete/lookup time of items in the dictionary is amortized constant time - O(1) - which means no matter how big the dictionary gets, the time it takes to find something remains relatively constant. This is highly desirable for high-speed lookups. The only downside is that the dictionary, by nature of using a hash table, is unordered, so you cannot easily traverse the items in a Dictionary in order. The SortedDictionary<TKey,TValue> is similar to the Dictionary<TKey,TValue> in usage but very different in implementation. The SortedDictionary<TKey,TValye> uses a binary tree under the covers to maintain the items in order by the key. As a consequence of sorting, the type used for the key must correctly implement IComparable<TKey> so that the keys can be correctly sorted. The sorted dictionary trades a little bit of lookup time for the ability to maintain the items in order, thus insert/delete/lookup times in a sorted dictionary are logarithmic - O(log n). Generally speaking, with logarithmic time, you can double the size of the collection and it only has to perform one extra comparison to find the item. Use the SortedDictionary<TKey,TValue> when you want fast lookups but also want to be able to maintain the collection in order by the key. The SortedList<TKey,TValue> is the other ordered associative container class in the generic containers. Once again SortedList<TKey,TValue>, like SortedDictionary<TKey,TValue>, uses a key to sort key-value pairs. Unlike SortedDictionary, however, items in a SortedList are stored as an ordered array of items. This means that insertions and deletions are linear - O(n) - because deleting or adding an item may involve shifting all items up or down in the list. Lookup time, however is O(log n) because the SortedList can use a binary search to find any item in the list by its key. So why would you ever want to do this? Well, the answer is that if you are going to load the SortedList up-front, the insertions will be slower, but because array indexing is faster than following object links, lookups are marginally faster than a SortedDictionary. Once again I'd use this in situations where you want fast lookups and want to maintain the collection in order by the key, and where insertions and deletions are rare. The Non-Associative Containers The other container classes are non-associative. They don't use keys to manipulate the collection but rely on the object itself being stored or some other means (such as index) to manipulate the collection. The List<T> is a basic contiguous storage container. Some people may call this a vector or dynamic array. Essentially it is an array of items that grow once its current capacity is exceeded. Because the items are stored contiguously as an array, you can access items in the List<T> by index very quickly. However inserting and removing in the beginning or middle of the List<T> are very costly because you must shift all the items up or down as you delete or insert respectively. However, adding and removing at the end of a List<T> is an amortized constant operation - O(1). Typically List<T> is the standard go-to collection when you don't have any other constraints, and typically we favor a List<T> even over arrays unless we are sure the size will remain absolutely fixed. The LinkedList<T> is a basic implementation of a doubly-linked list. This means that you can add or remove items in the middle of a linked list very quickly (because there's no items to move up or down in contiguous memory), but you also lose the ability to index items by position quickly. Most of the time we tend to favor List<T> over LinkedList<T> unless you are doing a lot of adding and removing from the collection, in which case a LinkedList<T> may make more sense. The HashSet<T> is an unordered collection of unique items. This means that the collection cannot have duplicates and no order is maintained. Logically, this is very similar to having a Dictionary<TKey,TValue> where the TKey and TValue both refer to the same object. This collection is very useful for maintaining a collection of items you wish to check membership against. For example, if you receive an order for a given vendor code, you may want to check to make sure the vendor code belongs to the set of vendor codes you handle. In these cases a HashSet<T> is useful for super-quick lookups where order is not important. Once again, like in Dictionary, the type T should have a valid implementation of GetHashCode() and Equals(), or you should provide an appropriate IEqualityComparer<T> to the HashSet<T> on construction. The SortedSet<T> is to HashSet<T> what the SortedDictionary<TKey,TValue> is to Dictionary<TKey,TValue>. That is, the SortedSet<T> is a binary tree where the key and value are the same object. This once again means that adding/removing/lookups are logarithmic - O(log n) - but you gain the ability to iterate over the items in order. For this collection to be effective, type T must implement IComparable<T> or you need to supply an external IComparer<T>. Finally, the Stack<T> and Queue<T> are two very specific collections that allow you to handle a sequential collection of objects in very specific ways. The Stack<T> is a last-in-first-out (LIFO) container where items are added and removed from the top of the stack. Typically this is useful in situations where you want to stack actions and then be able to undo those actions in reverse order as needed. The Queue<T> on the other hand is a first-in-first-out container which adds items at the end of the queue and removes items from the front. This is useful for situations where you need to process items in the order in which they came, such as a print spooler or waiting lines. So that's the basic collections. Let's summarize what we've learned in a quick reference table.  Collection Ordered? Contiguous Storage? Direct Access? Lookup Efficiency Manipulate Efficiency Notes Dictionary No Yes Via Key Key: O(1) O(1) Best for high performance lookups. SortedDictionary Yes No Via Key Key: O(log n) O(log n) Compromise of Dictionary speed and ordering, uses binary search tree. SortedList Yes Yes Via Key Key: O(log n) O(n) Very similar to SortedDictionary, except tree is implemented in an array, so has faster lookup on preloaded data, but slower loads. List No Yes Via Index Index: O(1) Value: O(n) O(n) Best for smaller lists where direct access required and no ordering. LinkedList No No No Value: O(n) O(1) Best for lists where inserting/deleting in middle is common and no direct access required. HashSet No Yes Via Key Key: O(1) O(1) Unique unordered collection, like a Dictionary except key and value are same object. SortedSet Yes No Via Key Key: O(log n) O(log n) Unique ordered collection, like SortedDictionary except key and value are same object. Stack No Yes Only Top Top: O(1) O(1)* Essentially same as List<T> except only process as LIFO Queue No Yes Only Front Front: O(1) O(1) Essentially same as List<T> except only process as FIFO   The Original Collections: System.Collections namespace The original collection classes are largely considered deprecated by developers and by Microsoft itself. In fact they indicate that for the most part you should always favor the generic or concurrent collections, and only use the original collections when you are dealing with legacy .NET code. Because these collections are out of vogue, let's just briefly mention the original collection and their generic equivalents: ArrayList A dynamic, contiguous collection of objects. Favor the generic collection List<T> instead. Hashtable Associative, unordered collection of key-value pairs of objects. Favor the generic collection Dictionary<TKey,TValue> instead. Queue First-in-first-out (FIFO) collection of objects. Favor the generic collection Queue<T> instead. SortedList Associative, ordered collection of key-value pairs of objects. Favor the generic collection SortedList<T> instead. Stack Last-in-first-out (LIFO) collection of objects. Favor the generic collection Stack<T> instead. In general, the older collections are non-type-safe and in some cases less performant than their generic counterparts. Once again, the only reason you should fall back on these older collections is for backward compatibility with legacy code and libraries only. The Concurrent Collections: System.Collections.Concurrent namespace The concurrent collections are new as of .NET 4.0 and are included in the System.Collections.Concurrent namespace. These collections are optimized for use in situations where multi-threaded read and write access of a collection is desired. The concurrent queue, stack, and dictionary work much as you'd expect. The bag and blocking collection are more unique. Below is the summary of each with a link to a blog post I did on each of them. ConcurrentQueue Thread-safe version of a queue (FIFO). For more information see: C#/.NET Little Wonders: The ConcurrentStack and ConcurrentQueue ConcurrentStack Thread-safe version of a stack (LIFO). For more information see: C#/.NET Little Wonders: The ConcurrentStack and ConcurrentQueue ConcurrentBag Thread-safe unordered collection of objects. Optimized for situations where a thread may be bother reader and writer. For more information see: C#/.NET Little Wonders: The ConcurrentBag and BlockingCollection ConcurrentDictionary Thread-safe version of a dictionary. Optimized for multiple readers (allows multiple readers under same lock). For more information see C#/.NET Little Wonders: The ConcurrentDictionary BlockingCollection Wrapper collection that implement producers & consumers paradigm. Readers can block until items are available to read. Writers can block until space is available to write (if bounded). For more information see C#/.NET Little Wonders: The ConcurrentBag and BlockingCollection Summary The .NET BCL has lots of collections built in to help you store and manipulate collections of data. Understanding how these collections work and knowing in which situations each container is best is one of the key skills necessary to build more performant code. Choosing the wrong collection for the job can make your code much slower or even harder to maintain if you choose one that doesn’t perform as well or otherwise doesn’t exactly fit the situation. Remember to avoid the original collections and stick with the generic collections.  If you need concurrent access, you can use the generic collections if the data is read-only, or consider the concurrent collections for mixed-access if you are running on .NET 4.0 or higher.   Tweet Technorati Tags: C#,.NET,Collecitons,Generic,Concurrent,Dictionary,List,Stack,Queue,SortedList,SortedDictionary,HashSet,SortedSet

    Read the article

  • How to efficiently resize an array of values, without boxing, used within a Dictionary<string, float[]>

    - by makerofthings7
    In the code below, Pages is defined as public SortedDictionary<DateTime, float[]> Pages { get; set; } I am trying to dynamically increase the size of this array. Can anyone tell how to increase the sized of the innermost float[]? var tt = currentContainer.Pages[dateTime]; Array.Resize<float>(ref tt, currentContainer.Pages.Count + 1); Fail 1 I tried the following code and get index out of range exception SortedDictionary<DateTime, float[]> Pages = new SortedDictionary<DateTime,float[]>(); float[] xx = new float[1]; xx[0] = 1; DateTime tempTime = DateTime.UtcNow; Pages.Add(tempTime, xx); var tt = Pages[tempTime]; Array.Resize<float>(ref tt, Pages.Count + 1); Pages[tempTime][1] = 2; Fail 2 The following gives a compile time error (property, index, or dynamic member can't be used as a ref value) SortedDictionary<DateTime, float[]> Pages = new SortedDictionary<DateTime,float[]>(); float[] xx = new float[1]; xx[0] = 1; DateTime tempTime = DateTime.UtcNow; Pages.Add(tempTime, xx); var tt = Pages[tempTime]; // The line below is different from Fail 1 above ... compile time error Array.Resize<float>(ref Pages[tempTime], Pages.Count + 1); Pages[tempTime][1] = 2; Question What is the most performant answer to resize this array? Would the answer change if it's likely that the final size will be 100-200 floats or 700-900 floats? What if I change my allocation size from +1 to +128? .. or larger?

    Read the article

  • Reversed Sorted Dictionary?

    - by Mark
    I have a SortedDictionary as defined like this: SortedDictionary<TPriority, Queue<TValue>> dict; But I want to sort the keys in reverse order. I assume I need set the Comparer, but what comparer do I use for a generic TPriority? Note that TPriority implements IComparable.

    Read the article

  • Best way to go about sorting 2D sprites in a "RPG Maker" styled RPG

    - by Aaron Stewart
    I am trying to come up with the best way to create overlapping sprites without having any issues. I was thinking of having a SortedDictionary and setting the Entity's key to it's Y position relative to the max bound of the simulation, aka the Z value. I'd update the "Z" value in the update method each frame, if the entity's position has changed at all. For those who don't know what I mean, I want characters who are standing closer in front of another character to be drawn on top, and if they are behind the character, they are drawn behind. I'm leery of using SpriteBatch back to front or front to back, I've been doing some searching and have been under the impression they are a bad idea. and want to know exactly how other people are dealing with their depth sorting. Just ultimately trying to come up with the best method of sorting for good practice before I get too far in to refactor the system effectively.

    Read the article

  • How do you sort a C# dictionary by value?

    - by kurious
    I often have a Dictionary of keys & values and need to sort it by value. For example, I have a hash of words and their frequencies, and want to order them by frequency. There's SortedList which is good for a single value (frequency), but I want to map it back to the word. SortedDictionary orders by key, not value. Some resort to a custom class, but what's the cleanest way?

    Read the article

  • How do I improve this design for dealing with intersecting date ranges and resolving date range conf

    - by derdo
    I am working on some code that deals with date ranges. I have pricing activities that have a starting-date and an end-date to set a certain price for that range. There are multiple pricing activities with intersecting date ranges. What I ultimately need is the ability to query valid prices for a date range. I pass in (jan1,jan31) and I get back a list that says jan1--jan10 $4 , jan11--jan19 $3 jan20--jan31 $4. There are priorities between pricing activities. Some type of pricing activities have high priority, so they override other pricing activities and for certain type of pricing activities lowest price wins etc. I currently have a class that holds these pricing activities and keeps a resolved pricing calendar. As I add new pricing activities I update the resolved calendar. As I write more tests/code, it started to get very complicated with all the different cases (pricing activities intersecting in different ways). I am ending up with very complicated code where I am resolving a newly added pricing activity. See AddPricingActivity() method below. Can anybody think of a simpler way to deal with this? Could there be similar code somewhere out there? Public class PricingActivity() { DateTime startDate; DateTime endDate; Double price; Public bool StartsBeforeEndsAfter (PricingActivity pAct) { // pAct covers this pricing activity } Public bool StartsMiddleEndsAfter (PricingActivity pAct){ // early part of pAct Itersects with later part of this pricing activity } //more similar methods to cover all the combinations of intersecting } Public Class PricingActivityList() { List<PricingActivity> activities; SortedDictionary<Date, PricingActivity> resolvedPricingCalendar; Public void AddPricingActivity(PricingActivity pAct) { //update the resolvedCalendar //go over each activity and find intersecting ones //update the resolved calendar correctly //depending on the type of the intersection //this part is getting out of hand….. } }

    Read the article

  • What collection object is appropriate for fixed ordering of values?

    - by makerofthings7
    Scenario: I am tracking several performance counters and have a CounterDescription[] correlate to DataSnapshot[]... where CounterDescription[n] describes the data loaded within DataSnapshot[n]. I want to expose an easy to use API within C# that will allow for the easy and efficient expansion of the arrays. For example CounterDescription[0] = Humidity; DataSnapshot[0] = .9; CounterDescription[1] = Temp; DataSnapshot[1] = 63; My upload object is defined like this: Note how my intent is to correlate many Datasnapshots with a dattime reference, and using the offset of the data to refer to its meaning. This was determined to be the most efficient way to store the data on the back-end, and has now reflected itself into the following structure: public class myDataObject { [DataMember] public SortedDictionary<DateTime, float[]> Pages { get; set; } /// <summary> /// An array that identifies what each position in the array is supposed to be /// </summary> [DataMember] public CounterDescription[] Counters { get; set; } } I will need to expand each of these arrays (float[] and CounterDescription[] ), but whatever data already exists must stay in that relative offset. Which .NET objects support this? I think Array[] , LinkedList<t>, and List<t> Are able to keep the data fixed in the right locations. What do you think?

    Read the article

  • Why is Dictionary.First() so slow?

    - by Rotsor
    Not a real question because I already found out the answer, but still interesting thing. I always thought that hash table is the fastest associative container if you hash properly. However, the following code is terribly slow. It executes only about 1 million iterations and takes more than 2 minutes of time on a Core 2 CPU. The code does the following: it maintains the collection todo of items it needs to process. At each iteration it takes an item from this collection (doesn't matter which item), deletes it, processes it if it wasn't processed (possibly adding more items to process), and repeats this until there are no items to process. The culprit seems to be the Dictionary.Keys.First() operation. The question is why is it slow? Stopwatch watch = new Stopwatch(); watch.Start(); HashSet<int> processed = new HashSet<int>(); Dictionary<int, int> todo = new Dictionary<int, int>(); todo.Add(1, 1); int iterations = 0; int limit = 500000; while (todo.Count > 0) { iterations++; var key = todo.Keys.First(); var value = todo[key]; todo.Remove(key); if (!processed.Contains(key)) { processed.Add(key); // process item here if (key < limit) { todo[key + 13] = value + 1; todo[key + 7] = value + 1; } // doesn't matter much how } } Console.WriteLine("Iterations: {0}; Time: {1}.", iterations, watch.Elapsed); This results in: Iterations: 923007; Time: 00:02:09.8414388. Simply changing Dictionary to SortedDictionary yields: Iterations: 499976; Time: 00:00:00.4451514. 300 times faster while having only 2 times less iterations. The same happens in java. Used HashMap instead of Dictionary and keySet().iterator().next() instead of Keys.First().

    Read the article

1 2  | Next Page >