Search Results

Search found 43 results on 2 pages for 'sortedlist'.

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

  • C# SortedList, getting value by key

    - by user1004039
    I have SortedList in descending order. public class MyComparer : IComparer<int> { public int Compare(int x, int y) { if (x.CompareTo(y) > 0) return -1; return 1; } } class Program { static void Main(string[] args) { SortedList<int, bool> myList = new SortedList<int, bool>(new MyComparer()); myList.Add(10, true); bool check = myList[10];//In this place an exception "Can't find key" occurs } } When SortedList created without my own IComparer the code works fine and no exception occurs.

    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

  • Is there a SortedList<T> class in .net ? (not SortedList<Key,Value> which is actually a kind of Sort

    - by Brann
    I need to sort some objects according to their contents (in fact according to one of their properties, which is NOT the key and may be duplicated between different objects) .net provides two classes (SortedDictionnary and SortedList), and both are some kind of Dictionaries. The only difference (AFAIK) is that SortedDictionnary uses a binary tree to maintain its state whereas SortedList does not and is accessible via an index. I could achieve what I want using a List, and then using its Sort() method with a custom implementation of IComparer, but it wouldn't be time-efficient as I would sort the whole List each time I insert a new object, whereas a good SortedList would just insert the item at the right position. What I need is a SortedList class with a RefreshPosition(int index) to move only the changed (or inserted) object rather than resorting the whole list each time an object inside changes. Am I missing something obvious ?

    Read the article

  • SortedList porting to Silverlight

    - by VLK
    Dear all It looks SortedList is excluded.. What do you think most appropriate out of existing collections? (to keep the same fast access and changes) Can silverlight Dictionary be permanently sorted? Best regards VLK

    Read the article

  • Function returning pointer to struct

    - by GammaGuy
    I am having some issues with code that is returning a pointer to a struct declared inside a class. Here is my code so far: SortedList.h #ifndef SORTEDLIST_H #define SORTEDLIST_H class SortedList{ public: SortedList(); ... private: struct Listnode { Student *student; Listnode *next; }; static Listnode *copyList (Listnode *L); }; #endif SortedList.cpp #include "SortedList.h" ... // Here is where the problem lies Listnode SortedList::*copyList(Listnode *L) { return 0; // for NULL } Apparently, the copy list method wont compile. I am using Microsoft Visual Studio and the compiler tells me that "Listnode" is unidentified. When I try to compile, here is whhat I get: 1>------ Build started: Project: Program3, Configuration: Debug Win32 ------ 1> SortedList.cpp 1>c:\users\owner\documents\college\fall 2012\cs 368 - learn c++\program3\program3\sortedlist.cpp(159): error C2657: 'SortedList::*' found at the start of a statement (did you forget to specify a type?) 1>c:\users\owner\documents\college\fall 2012\cs 368 - learn c++\program3\program3\sortedlist.cpp(159): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1>c:\users\owner\documents\college\fall 2012\cs 368 - learn c++\program3\program3\sortedlist.cpp(159): error C2065: 'L' : undeclared identifier 1>c:\users\owner\documents\college\fall 2012\cs 368 - learn c++\program3\program3\sortedlist.cpp(159): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1>c:\users\owner\documents\college\fall 2012\cs 368 - learn c++\program3\program3\sortedlist.cpp(159): fatal error C1903: unable to recover from previous error(s); stopping compilation ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== Help would be greatly appreciated...ASAP

    Read the article

  • Re-ordering collection C#

    - by Adam
    Hi - I have a problem which I cant seem to find answer to through searches (either that or I am searching for the completely wrong thing!). I have a list of items called "Top 10" in a sortedlist item that is populated from my DB (SortedList where int is position and string is item). I want to be able to move items up & down the list order at the click of a button and then save the new order back to the DB. I am OK with the DB part it is just the re-ordering I am really struggling with - is a sortedlist the correct collection for this? Many thanks for any advice offered.

    Read the article

  • Is there a non-unique-key sorted list generic collection in C#?

    - by kdt
    I'm a bit surprised by System.Collections.Generic.SortedList, in that It requires me to use <key, value> instead of <value>(comparer) It only allows on entry per value These seem quirky in the way I want to use it (although I'm sure they're just right for other situations). Is there another collection that doesn't have these two characteristics?

    Read the article

  • C++ scoping error

    - by Pat Murray
    I have the following code: #include "Student.h" #include "SortedList.h" using namespace std; int main() { // points to the sorted list object SortedList *list = new SortedList; //This is line 17 // array to hold 100 student objects Student create[100]; int num = 100000; // holds different ID numbers // fills an array with 100 students of various ID numbers for (Student &x : create) { x = new Student(num); num += 100; } // insert all students into the sorted list for (Student &x : create) list->insert(&x); delete list; return 0; } And I keep getting the compile time error: main.cpp: In function ‘int main()’: main.cpp:17: error: ‘SortedList’ was not declared in this scope main.cpp:17: error: ‘list’ was not declared in this scope main.cpp:17: error: expected type-specifier before ‘SortedList’ main.cpp:17: error: expected `;' before ‘SortedList’ main.cpp:20: error: ‘Student’ was not declared in this scope main.cpp:20: error: expected primary-expression before ‘]’ token main.cpp:20: error: expected `;' before ‘create’ main.cpp:25: error: expected `;' before ‘x’ main.cpp:31: error: expected primary-expression before ‘for’ main.cpp:31: error: expected `;' before ‘for’ main.cpp:31: error: expected primary-expression before ‘for’ main.cpp:31: error: expected `)' before ‘for’ main.cpp:31: error: expected `;' before ‘x’ main.cpp:34: error: type ‘<type error>’ argument given to ‘delete’, expected pointer main.cpp:35: error: expected primary-expression before ‘return’ main.cpp:35: error: expected `)' before ‘return’ My Student.cpp and SortedList.cpp files compile just fine. They both also include .h files. I just do not understand why I get an error on that line. It seems to be a small issue though. Any insight would be appreciated. UPDATE1: I originally had .h files included, but i changed it when trying to figure out the cause of the error. The error remains with the .h files included though. UPDATE2: SortedList.h #ifndef SORTEDLIST_H #define SORTEDLIST_H #include "Student.h" /* * SortedList class * * A SortedList is an ordered collection of Students. The Students are ordered * from lowest numbered student ID to highest numbered student ID. */ class SortedList { public: SortedList(); // Constructs an empty list. SortedList(const SortedList & l); // Constructs a copy of the given student object ~SortedList(); // Destructs the sorted list object const SortedList & operator=(const SortedList & l); // Defines the assignment operator between two sorted list objects bool insert(Student *s); // If a student with the same ID is not already in the list, inserts // the given student into the list in the appropriate place and returns // true. If there is already a student in the list with the same ID // then the list is not changed and false is returned. Student *find(int studentID); // Searches the list for a student with the given student ID. If the // student is found, it is returned; if it is not found, NULL is returned. Student *remove(int studentID); // Searches the list for a student with the given student ID. If the // student is found, the student is removed from the list and returned; // if no student is found with the given ID, NULL is returned. // Note that the Student is NOT deleted - it is returned - however, // the removed list node should be deleted. void print() const; // Prints out the list of students to standard output. The students are // printed in order of student ID (from smallest to largest), one per line private: // Since Listnodes will only be used within the SortedList class, // we make it private. struct Listnode { Student *student; Listnode *next; }; Listnode *head; // pointer to first node in the list static void freeList(Listnode *L); // Traverses throught the linked list and deallocates each node static Listnode *copyList(Listnode *L); // Returns a pointer to the first node within a particular list }; #endif #ifndef STUDENT_H #define STUDENT_H Student.h #ifndef STUDENT_H #define STUDENT_H /* * Student class * * A Student object contains a student ID, the number of credits, and an * overall GPA. */ class Student { public: Student(); // Constructs a default student with an ID of 0, 0 credits, and 0.0 GPA. Student(int ID); // Constructs a student with the given ID, 0 credits, and 0.0 GPA. Student(int ID, int cr, double grPtAv); // Constructs a student with the given ID, number of credits, and GPA.\ Student(const Student & s); // Constructs a copy of another student object ~Student(); // Destructs a student object const Student & operator=(const Student & rhs); // Defines the assignment operator between two student objects // Accessors int getID() const; // returns the student ID int getCredits() const; // returns the number of credits double getGPA() const; // returns the GPA // Other methods void update(char grade, int cr); // Updates the total credits and overall GPA to take into account the // additions of the given letter grade in a course with the given number // of credits. The update is done by first converting the letter grade // into a numeric value (A = 4.0, B = 3.0, etc.). The new GPA is // calculated using the formula: // // (oldGPA * old_total_credits) + (numeric_grade * cr) // newGPA = --------------------------------------------------- // old_total_credits + cr // // Finally, the total credits is updated (to old_total_credits + cr) void print() const; // Prints out the student to standard output in the format: // ID,credits,GPA // Note: the end-of-line is NOT printed after the student information private: int studentID; int credits; double GPA; }; #endif

    Read the article

  • Need sorted dictionary designed to find values with keys less or greater than search value

    - by Captain Comic
    Hi I need to have objects sorted by price (decimal) value for fast access. I need to be able to find all objects with price more then A or less than B. I was thinkg about SortedList, but it does not provide a way to find ascending or descending enumerator starting from given key value (say give me all objects with price less than $120). Think of a system that accepts items for sell from users and stores them into that collection. Another users want to find items cheaper than $120. Basically what i need is tree-based collection and functionality to find node that is smaller\greater\equal to provided key. Please advice.

    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

  • C# Linq: Restructuring object

    - by Ben
    I'd like to take an object like this: SortedList<string, SortedList<int, SortedList<DateTime, double>>> Data and, for a given 'int' value (key of first nested sorted list), restructure it like this: SortedList<DateTime, SortedList<string, double>> or, better yet, this: SortedList<DateTime, double[]> where each 'double[]' has as many elements as there are KeyValue pairs in the SortedList. I'm guessing Linq is the way to go, but can't figure it out. Thanks for any suggestions.

    Read the article

  • An Efficient data structure for Sorted List

    - by holydiver
    I want to save my objects according to a key in the attributes of my object in a sorted fashion. Later on I'll access these objects sequentially from max key to min key. I'll do some search tasks as well. I consider to use either AVL tree or RB Tree. As far as i know they are nearly equivalent in theory(Both have O(logn)). But in practice which one might be better in performance in my situation. And is there a better alternative than those, considering that I'll mostly do insert and sequentially access to the ds.

    Read the article

  • Merging some sorted lists with unknown order sequence

    - by Gabriel
    I've some sorted lists with variable number of elements. I wold like to merge the lists into one big list which contains all other lists in same order, without duplicates. Example: 1. XS,M,L,XL 2. S,M,XXL 3. XXS,XS,S,L Result: XXS,XS,S,M,L,XL,XXL The function should notify, if there are elements which have ambiguous positions. Here, it would be XXL and I need to specify its position after XL.

    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

  • Visual Studio 2008 having problems with namespaces when used as type in Generic coolection

    - by patrick
    I just upgraded last week from Visual Studio 2005 to 2008. I am having an issue with compiler resolving namespaces when I use a class as a type in a Generic collection. Intellisense recognizes the class and the compiler generates no errors when I use the class except when it is a type in a Generic collection declaration either as return type for a Property or as a parameter to a method. This is happening in my only project that is targeting the 3.5 framework, but changing the project containing the class to use the 3.5 framework doesn't fix the problem. Examples Compile fine MyClass myClass = new MyClass(); SortedList <DateTime,MyClass> listOfClasses = new SortedList<DateTime,MyClass> Compile error - Namespace could not be found public SortedList<DateTime,MyClass> ClassList { get; set; } private void DoSomethingToLists(SortedList<DateTime,MyClass> classList) Intellisense has no problem resolving the namespace, only the compiler. Is this a known bug or am I missing something obvious? Will SP1 fix it? I was able to create a new library containing just this class targeting 3.5 and am now able to successfully use this in both 3.5 and 2.0 projects. My guess is that even though I tried to change the target of my original library, since it was still referencing 2.0 projects there was some conflict.

    Read the article

  • Why does sorted list have to have a key value pair?

    - by clawson
    If I just want a sorted list of just dates, integers, or doubles is it really necessary to have to define a SortedList(of Integer, Integer)? Seems intriguing to me, but may just be trival. I'd prefer just to use a SortedList(of Integer). (This question is in relation to the .Net generic collections)

    Read the article

  • There are 2 jobs available - which one sounds better all round [closed]

    - by Steve Gates
    I am currently employed at a company where we scrape by each year breaking even, sometimes having a little profit. The development environment is very relaxed and we have a laugh. My colleagues are not interested in improving their knowledge unless they have to, so trying to get them to adopt things like TDD is a non-starter. My development manager is stuck in .Net 2 land and refuses to use things like LINQ. He over complicates architecture and writes very unreadable code, heres an example SortedList<int,<SortedList<int,SortedList<int, MyClass>>>> The MD of the company has no drive and lets the one sales guy bring in the contracts. We are not busy all the time and this allows me time to look at new technology and learn. In terms of using things like TDD, my development manager has no problem with it and can kind of see the purpose of it, he just wont use it himself. This means I am alone in learning new things and am often resorting to StackOverflow to make sure I get things right. The company has a lot of flexibility, I can work from home if needs be and when my daughter was born they let me work from home 1 day a week however they expect this flexibility in return often asking me to travel occasionally on a Friday afternoon for the following week. Sometimes its abroad. We are also pretty much on call 24/5 as we have engineers in various countries. Also we have no testers so most of the testing is done by us developers and some testing by engineers. Either way no-one likes testing! I have been offered a role at a company I worked at 5 years ago. They were quite Victorian in their working practices but it appears to have relaxed now although I suspect still reasonably formal. There is a new team of developers I don't know and they are about to move to new offices. The team lead is a guy that was there when I was and I get the impression he takes his role seriously and likes his formal procedures and documentation. I think some of the Victorian practices may have rubbed off on him. However he did say if things crop up then as long as I can trust the person they can work at home although he prefers people in the office. The team uses SCRUM, TDD and SOLID design principles so they are quite up to date in technology. They are reasonably Microsoft focused. It appears the Technical Director might be the R&D man and research new technology on his own not allowing developers to play with new technology. He possibly might be a super developer and makes all the decisions that no can argue with. They are currently moving to Entity Framework away from NHibernate based on issues that their queries seem to fail sometimes and they feel NHibernate is stagnant. They have analysts and a QA team. The MD is focused and they are an expanding company making profit each year. I'm not sure what the team morale is and whether they have a laugh. When I had a tour around the office they were there in dead silence. I'm really unsure which role is the best for me and going with my gut instinct is useless as I'm not sure what my gut is telling me. Based on the information above which role would you choose and why?

    Read the article

  • Python beginner having trouble running code

    - by Protean
    For some reason this code will not seem to run in the interpreter. When I hit F5 nothing happens, not even the debugger seems to recognize it. I assume it has something to do with the class, as when removed the interpreter seems to recognize the rest of the code. Please tell me what I am doing wrong. Edit: I have restarted the interpreter multiple times, any other piece of code I try to load runs fine, just this one is having trouble. print ('Why won't this work?') class sorting_class: def __init__(self): self.order = ['a', 'b', 'c', 'd'] self.globali = 0 self.orderi = 0 self.sortedlist = [] def sort(self, array): carry, leave = [] for arrayi in array: print ('run', arrayi) if self.order[self.orderi] == arrayi[self.globali]: carry.append(arrayi) else: if self.globali != 0: leave.append(arrayi) return carry, leave def srt(self, array): globalii = 0 carry, leave = my.sort(array) while len(self.sortedlist) != len(array): if len(self.carry) == 1: self.sortedlist.append(carry) arrayt = leave self.globali = 1 self.orderi = 0 carry, leave = my.sort(arrayt) elif len(self.carry) == 0: if len(self.leave) != 0: arrayt = leave self.globali = 1 self.orderi += 1 my.sort(arrayt) else: self.arrayt globalii += 1 self.orderi = globalii self.globali = 0 my.sort(arrayt) self.orderi = 0 else: arrayt = carry carry = [] self.globali += 1 carry, leave += my.sort(arrayt) my = sorting_class() x = ['ac', 'bc' ,'ab', 'da'] my.srt(x)

    Read the article

  • adding header row to gridview won't allow you to save the last item row

    - by Lex
    I've modified my GridView to have an extra Header row, however that extra row has caused my grid view row count to be incorrect. Basically, when I want to save the Gridview now, it doesn't recognize the last item line. In my current test I have 5 Item Lines, however only 4 of them are being saved. My code for creating the additional header Line: protected void gvStatusReport_RowDataBound(object sender, GridViewRowEventArgs e) { // This grid has multiple rows, fake the top row. if (e.Row.RowType == DataControlRowType.Header) { SortedList FormatCells = new SortedList(); FormatCells.Add("1", ",6,1"); FormatCells.Add("2", "Time Spent,7,1"); FormatCells.Add("3", "Total,2,1"); FormatCells.Add("4", ",6,1"); GetMultiRowHeader(e, FormatCells); } } The function to create a new row: public void GetMultiRowHeader(GridViewRowEventArgs e, SortedList GetCels) { GridViewRow row; IDictionaryEnumerator enumCels = GetCels.GetEnumerator(); row = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal); while (enumCels.MoveNext()) { string[] count = enumCels.Value.ToString().Split(Convert.ToChar(",")); TableCell cell = new TableCell(); cell.RowSpan = Convert.ToInt16(count[2].ToString()); cell.ColumnSpan = Convert.ToInt16(count[1].ToString()); cell.Controls.Add(new LiteralControl(count[0].ToString())); cell.HorizontalAlign = HorizontalAlign.Center; row.Cells.Add(cell); } e.Row.Parent.Controls.AddAt(0, row); } Then when I'm going to save, I loop through the rows: int totalRows = gvStatusReport.Rows.Count; for (int rowNumber = 0; rowNumber < totalRows; rowNumber++) { However the first line doesn't seem to have any of the columns that the item row has, and the last line doesn't even show up. My problem is that I do need the extra header line, but what is the best way to fix this?

    Read the article

  • Python beginer having trouble running code

    - by Protean
    For some reason this code will not seem to run in the interpreter. When I hit F5 nothing happens, not even the debugger seems to recognize it. I assume it has something to do with the class, as when removed the interpreter seems to recognize the rest of the code. Please tell me what I am doing wrong. Edit: I have restarted the interpreter multiple times, any other piece of code I try to load runs fine, just this one is having trouble. print ('Why won't this work?') class sorting_class: def __init__(self): self.order = ['a', 'b', 'c', 'd'] self.globali = 0 self.orderi = 0 self.sortedlist = [] def sort(self, array): carry, leave = [] for arrayi in array: print ('run', arrayi) if self.order[self.orderi] == arrayi[self.globali]: carry.append(arrayi) else: if self.globali != 0: leave.append(arrayi) return carry, leave def srt(self, array): globalii = 0 carry, leave = my.sort(array) while len(self.sortedlist) != len(array): if len(self.carry) == 1: self.sortedlist.append(carry) arrayt = leave self.globali = 1 self.orderi = 0 carry, leave = my.sort(arrayt) elif len(self.carry) == 0: if len(self.leave) != 0: arrayt = leave self.globali = 1 self.orderi += 1 my.sort(arrayt) else: self.arrayt globalii += 1 self.orderi = globalii self.globali = 0 my.sort(arrayt) self.orderi = 0 else: arrayt = carry carry = [] self.globali += 1 carry, leave += my.sort(arrayt) my = sorting_class() x = ['ac', 'bc' ,'ab', 'da'] my.srt(x)

    Read the article

  • Problem with for-loop in python

    - by Protean
    This code is supposed to be able to sort the items in self.array based upon the order of the characters in self.order. The method sort runs properly until the third iteration, unil for some reason the for loop seems to repeat indefinitely. What is going on here? class sorting_class: def __init__(self): self.array = ['ca', 'bd', 'ac', 'ab'] #An array of strings self.arrayt = [] self.globali = 0 self.globalii = 0 self.order = ['a', 'b', 'c', 'd'] #Order of characters self.orderi = 0 self.carry = [] self.leave = [] self.sortedlist = [] def sort(self): for arrayi in self.arrayt: #This should only loop for the number items in self.arrayt. However, the third time this is run it seems to loop indefinitely. print ('run', arrayi) #Shows the problem if self.order[self.orderi] == arrayi[self.globali]: self.carry.append(arrayi) else: if self.globali != 0: self.leave.append(arrayi) def srt(self): self.arrayt = self.array my.sort() #First this runs the first time. while len(self.sortedlist) != len(self.array): if len(self.carry) == 1: self.sortedlist.append(self.carry) self.arrayt = self.leave self.leave = [] self.carry = [] self.globali = 1 self.orderi = 0 my.sort() elif len(self.carry) == 0: if len(self.leave) != 0: #Because nothing matches 'aa' during the second iteration, this code runs the third time" self.arrayt = self.leave self.globali = 1 self.orderi += 1 my.sort() else: self.arrayt = self.array self.globalii += 1 self.orderi = self.globalii self.globali = 0 my.sort() self.orderi = 0 else: #This is what runs the second time. self.arrayt = self.carry self.carry = [] self.globali += 1 my.sort() my = sorting_class() my.srt()

    Read the article

1 2  | Next Page >