Click here to Skip to main content
15,886,199 members
Everything / Collections

Collections

collections

Great Reads

by honey the codewitch
Implementing full list support over custom data structures in .NET
by Sander Rossel
Using Venn diagrams to visualize sets.
by honey the codewitch
Easily implement efficient backtracking capabilities over any enumeration
by Rene Bustos
WCF WebService IN VB.NET Response JSON

Latest Articles

by Gerardo Recinto
In-memory B-Tree sorted dictionary
by Bohdan Stupak
Batching is a nice technique that allows you to handle big amounts of data gracefully. Directory.EnumerateFiles is the API that allows you to organize batch processing for the directory with a large number of files.
by Dev Leader
This article is follow up content to previous articles I've written about iterators and collections, but the benchmark results were NOT what I expected!
by Pavel Bashkardin
Represents a C# generic implementation of the NameValueCollection

All Articles

Sort by Score

Collections 

17 Nov 2019 by honey the codewitch
Implementing full list support over custom data structures in .NET
9 Nov 2015 by Sander Rossel
Using Venn diagrams to visualize sets.
23 Dec 2019 by honey the codewitch
Easily implement efficient backtracking capabilities over any enumeration
16 May 2017 by Rene Bustos
WCF WebService IN VB.NET Response JSON
23 Mar 2021 by honey the codewitch
Make your code more efficient by hacking your compiler to improve its optimization capabilities
12 Aug 2023 by Bohdan Stupak
Batching is a nice technique that allows you to handle big amounts of data gracefully. Directory.EnumerateFiles is the API that allows you to organize batch processing for the directory with a large number of files.
6 Feb 2020 by honey the codewitch
A circular buffer implementing IList
24 Feb 2020 by honey the codewitch
A relatively safe, simple, yet high performance technique for using lists as dictionary keys.
16 Aug 2011 by Damian Flynn
Here's a couple of gems...From IList to DataTable.From DataTable to array of T.// DataTable: from IListpublic static DataTable ToDataTable(this IList iList){ DataTable dataTable = new DataTable(); PropertyDescriptorCollection propertyDescriptorCollection = ...
5 Dec 2019 by honey the codewitch
Fills a gap in Microsoft's Queue offering with an alternative allowing efficient indexed access
14 Jul 2011 by Sergey Alexandrovich Kryukov
The point of hashing and Dictionary is using the unique keys bur also fast search by the key, which you can call indexing. The speed of search is of O(1), see http://en.wikipedia.org/wiki/Big_O_notation[^]. If you think about it, you will understand that a non-unique key cannot be used with...
1 Aug 2011 by Abhinav S
Nothing, as far as your example is concerned.In the first case, you could actually define the array count in the first statement but add values to it later.E.g.List withParentheses = new List[4];withParentheses[0]=1;withParentheses[1]=2;In the second case, you don't have that...
19 Jul 2023 by PIEBALDconsult
If you have access to the code for the Address class, you can add the ability for them to compare themselves. The following is a very naïve example. Comparing addresses is a very complex topic with many pitfalls. public partial class Address...
17 Mar 2024 by Pete O'Hanlon
You cannot tell if an object has been changed using an ObservableCollection. The way to do this is to use INotifyPropertyChanged and raise the PropertyChanged event whenever you change the value in a property.
30 May 2011 by Sergey Alexandrovich Kryukov
You don't need a data special structure for the tree. Having such data type in a standard library would be absolutely redundant, because a tree is just a list of some elements which has a "children" member of the same type.Here is the simplest example:using Tree =...
13 Aug 2011 by Vano Maisuradze
Very nice!I've modified ToCollection(this DataTable dt) extension function, so if DataTable column names and class property names are different, then you can use this alternative:public static List ToCollection(this DataTable table, Dictionary dic){ List lst = new...
5 Jan 2012 by Mehdi Gholam
ArrayList is a collection for any type of object, which should not be used because of boxing and unboxing performance, you should use List instead. You usually use this for storing and iterating over as is.Hashtable is a collection for rapid storing and retrieval based on the...
20 Feb 2012 by Fredrik Bornander
Deferred execution is the culprit here (I think), the sort isn't run until the result is enumerated so when you do this;orderedList.Contains(923456); you're resorting the list again for every iteration. ToList forces the result to be enumerated up front.You can see this by changing...
13 Oct 2017 by Karthik_Mahalingam
try string[] userDataKeys = config.Where(x => x.Contains("userdata.")).Select(x => x.Replace("userdata.", "") ).ToArray();
6 Apr 2010 by William Winner
OK..there are a lot of problems with your code. Let's look at some of your code:public static frmMain Main = null;//...more codeprivate void btnAdd_Click(object sender, EventArgs e){ frmAdd add = new frmAdd(); add.Show(); Main = this; this.Hide(); ...
5 Jan 2012 by Wendelius
Fully agree on Mehdi's solution. Also few links you may find useful:- A Comparison of .NET Collections[^]- Cheat Sheet: Speed of Common Operations[^]
20 Feb 2012 by Sander Rossel
I just stumbled upon an oddity in IOrderedEnumerable.Contains[^] and was wondering if more people here had the problem or if it is just me...Consider the following code:using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace...
21 Dec 2017 by rtybase
An use case for ConcurrentHashMap
4 Sep 2012 by BeStelios
public class ViewModel { ObservableCollection CustomerList = new ObservableCollection(); public ICollectionView BlueCustomersView { get; private set; } public ICollectionView BlackCustomersView { get; private set; } public ICollectionView...
19 Jun 2014 by Maciej Los
If you want to know the way you can serialize and deserialize custom class collection, this tip is for you.
18 Feb 2015 by PIEBALDconsult
Here's an example of a class that uses two Dictionaries.I do caution you about your first criterion as I'm sure my solution will have trouble if a value's priority is changed. DumbStuff.PriorityDictionary d = new...
14 Sep 2015 by Matt T Heffron
According to Expresso[^], this regex will give what you want:((?>"[^"]+")|[^;]+)It will splitFrance;Japan;Russia;China;"India;New-Delhi";"NewZeland;Wellington";EnglandintoFranceJapanRussiaChina"India;New-Delhi""NewZeland;Wellington"EnglandThen you can use .Trim('"') on the...
17 Jul 2019 by ireland94
This program demonstrates the methodology needed for by directional messaging between a Java FX foreground and 1 or more background threads.
13 Oct 2017 by Pete O'Hanlon
You're almost there. First you need to identify which records contain userdata.. A where clause helps here:config.Where(x => x.StartsWith("userdata.")).Select(x => x.Replace("userdata.", string.Empty)).ToList();
21 Feb 2019 by Ralf Meier
I modified your (for me relevant) Code a little bit to make it work. I think that will help you : Imports System.Windows.Forms.Design Imports System.ComponentModel Public Class CustomerComponent Inherits Component ...
17 Mar 2023 by Dev Leader
This article is follow up content to previous articles I've written about iterators and collections, but the benchmark results were NOT what I expected!
14 Apr 2010 by William Winner
Do you really expect us to do your homework for you...ok..here you go:C# ArrayList[^] and C# HashTable[^]
8 Jun 2010 by Chris Trelawny-Ross
There is no need to remove and re-add the inner dictionary when removing an item from it, so you can just do:// To remove outer[1][2]outer[1].Remove(2);
25 Apr 2011 by OriginalGriff
Array is a fixed type: it's size must be known in advance of adding the elements. With the other collection types, you do not need to know the size in advance. You cannot extend the size of an array: you have to declare a bigger array and copy all the existing elements into it.Additionally,...
30 May 2011 by Monjurul Habib
http://www.google.com/#hl=en&sugexp=ldymls&xhr=t&q=generic+tree+c+sharp&cp=14&pq=generic%20c%23%20&pf=p&sclient=psy&source=hp&aq=0v&aqi=&aql=&oq=generic++tree+C%23+&pbx=1&bav=on.2,or.r_gc.r_pw.&fp=f99e8c741a251b45&biw=1024&bih=558[^]
30 May 2011 by Espen Harlinn
Just a followup on SAKryukovs' answer, how about:public class TreeNode{ public class ChildList : BindingList > {} private ChildList children; private T data; public TreeNode() { children = new ChildList(); } public TreeNode(T...
13 Jun 2011 by parmar_punit
class Person{ public string Name { get; set; } public Fruits FruitsItem { get; set; } //now you can get the details like this.... List _allPerson = new List(); private List CreateCollection() { _allPerson.Add(new Person { Name =...
29 Sep 2011 by Al Moje
Hi,In your DAL I thing you should do it this way to return theList of User Public Shared Function SelectAll() As List(Of User) 'Create List Of User Dim userColl As New List(Of User) Try 'select * from User _sqlConn = New...
26 Dec 2011 by Sergey Alexandrovich Kryukov
Polymorphism is not a phenomena which can be allowed or prohibited. Generics cannot change the situation, because they have nothing to do with polymorphism, because they have nothing to do with inheritance, "virtual" and late binding. Generics are static; any type which can be instantiated...
4 Apr 2012 by pinx
List subclass for limited number of items and fast search.
20 Aug 2012 by Clifford Nelson
You have two ways to associate Employees and Departments using objects. One is to have a Department property in the Employee object and the other is to have a collection of Employee objects in the Department object. You will also, at the minimum have either a collection of all Department or all...
26 Sep 2012 by cpquest
Hi all,i have implemented a Extension method for ICollection f in project that bacically i am trying to do some datagrid related operation on ApplicationIdle state. here is the code. public static class CollectionExtension { /// /// Set item Binding to...
26 Sep 2012 by Clifford Nelson
I have used the Dispatcher, and it does not seem to be very reliable. Had much more luck with tasks: First get a TaskScheduler from somewhere that is on the UI thread:TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();Then in the place you need to make changes...
31 Oct 2012 by Ilya Holinov
var titles = A.Bs .Select(b => b.Title) .Union(A.Bs.SelectMany(b => b.Cs, (b, c) => c.Title)) .Distinct();
4 Feb 2013 by Santhosh Kumar Jayaraman
If you're using .NET 3.5, you can use DataTableExtensions.AsEnumerable (an extension method) and then if you really need a List instead of just IEnumerable you can call Enumerable.ToList:IEnumerable sequence = dt.AsEnumerable();orList list =...
7 Aug 2013 by ridoy
I think this should help you..Binding a generic collection to a DataGridView via Visual Basic 2008 code[^]And to filter collection you can follow..FilterDatainaCollectionSettheFilterpropertytoaFilterEventHandler.htm[^]
9 Oct 2014 by Richard Deeming
You might be able to get away with specifying the correct generic type name:System.Collections.Generic.List`1[BusinessObject.Products]However, the simplest solution would be to use a custom non-generic collection class:using System;using System.Collections.Generic;namespace...
23 Nov 2014 by Kornfeld Eliyahu Peter
MSDN:... the capacity is automatically increased by reallocating the internal array before copying the old elements and adding the new elements.http://msdn.microsoft.com/en-us/library/system.collections.collectionbase.capacity(v=vs.110).aspx[^]
17 Jan 2015 by BillWoodruff
using System.Collections.ObjectModel;namespace TestObservableCollection{ public class WorkSpace { public int ID { set; get; } public string Name { set; get; } public WorkSpace(int id, string name) { ID = id; Name =...
18 Feb 2015 by Herbisaurus
I need a collection of objects that will: * allow get, set functionality object via a key (like in a dictionary)* I need to iterate through the collection in a sorted manner, ordered by a "Priority" value* the priority allows multiple values. * the keys can be an int or a string, it...
19 Feb 2015 by SaranshSrivastava
Use AddRange() method of List instead Add. Like below:string[] input = { "Apple", "Orange", "Apricots" }; List fruits= new List(); Console.WriteLine("\nAddRange(fruits)"); ...
24 Jul 2015 by Ralf Meier
You must add the following line to your Property : Public ReadOnly Property Items As ExplorerBarItemCollection Get Return fItems End...
14 Sep 2015 by Riya-Pandey
I am having trouble in splitting string. I mean i am able to split the string but i also need to put a certain condition as to how to split.My strings text is France;Japan;Russia;China;"India;New-Delhi";"NewZeland;Wellington";EnglandI want to split string using ; as delimiter....
14 Sep 2015 by Patrice T
Solution 1: Never use as separator a char that appear in data.I guess you see why it is a problem.If you can change your csv file, use a separator that is unused in that data at csv generation.Solution 2: it gets pretty complicated. string csvline...
7 Jan 2016 by debashishPaul
You are trying to convert the ArrayList to Guid.TaxFieldID = new Guid(Alist .ToString ())Use an iterator (for / while / foreach) to iterate through the ArrayList items and convert each item.
7 Jan 2016 by Maciej Los
On the first look, below line may throw an error:TaxFieldID = new Guid(Alist .ToString ()),Guid constructor does not accept array of strings, it accepts single string.Guid g = new Guid(Alist[0]);See: Guid Constructor (System)[^]
25 Apr 2016 by Karthik_Mahalingam
Add this in your second loopforeach (KeyValuePair pair in listcps) { foreach (var counterparty in cpResponse.counterpartyList) { if (noNexusCpsdict.ContainsKey(counterparty.CounterpartyId)) ...
30 Jun 2016 by Mohibur Rashid
In your boolean check function you are assigning arr to temp. arr and temp are same objects. If you reverse temp, you are reversing arr. You better look at how to clone to an object, not the assignment operator
16 Mar 2017 by Jochen Arndt
Your tester does not know what he talks about. If you specify the same address multiple times, it will be send multiple times. It does not care in which of the destination fields ("To", "Cc", "Bcc") the address is specified. The SMTP server will parse all fields and forward the message to each...
13 Oct 2017 by Maciej Los
There's no need to use .StartWith or .Contains method. Simple .Replace should be enough :) var result = config.Select(x=>x.Replace("userdata.", string.Empty)).ToList(); Of course, if you want to return only data with member word, you can use: var result =...
24 Feb 2018 by BillWoodruff
If you are serious about understanding time performance in .NET, I suggest you learn to use one of these open-source tools: BenchmarkDotNet (what I use) [^], or, AppMetrics [^]. By doing this, you will become a better programmer. Scott Hanselman wrote about BenchMark in 2016: [^]. Both these...
10 Jun 2019 by CPallini
Try: import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); List list = new ArrayList(); while(t-- > 0) { list.add(sc.nextInt()); ...
26 Apr 2020 by OriginalGriff
Google is your friend: Be nice and visit him often. He can answer questions a lot more quickly than posting them here... A very quick search using your subject as the search term gave over 2 million hits: implement a hash table using only...
14 Jan 2022 by Electro_Attacks
Ok guys, I've managed to get my code working, somehow... It's not tested completely, but it looks promising to me :) If you find any errors doing testing, or any suggestions how I can improve my code, let me know... You might need to comment...
31 Jan 2022 by Richard Deeming
A collection initializer can work with multiple parameters - for example: private static Dictionary _dataStructure = new() { ["Foo"] = new MyDataPlot { { 0, 1 }, { 2, 3 }, { 4, 5 }, }, }; ...
6 Mar 2024 by Graeme_Grant
List is not a bindable collection. You need to use the ObservableCollection Class (System.Collections.ObjectModel) | Microsoft Learn[^]. Here is a working solution for a similar question. Create a new project and add this code: 1. Classes: ...
25 Nov 2009 by Eightbitz
Having trouble iterating through a stack for a "Simon" game. I created a random string generator to populate a stack to iterate through to trigger timers, and I can only get it to iterate the same index over and over. How do I get it to return to timer() and go to the next item in the stack (mySimon
29 Dec 2009 by saleem_deek
I read your article,and i thought that i finally found what i'm searching for,but it was not enough:(..I'm trying to use your way to call my C# DLL from VB6,using collections,and it's not working,when i try to assign a new collection from the C# dll function,it gives me one of these two...
29 Dec 2009 by dan!sh
I would be better if you post the question under the forum below the article itself. That way the article writer will be notified and will help you out.
19 Feb 2010 by JimBob SquarePants
Hi all,I've been writing a provider that uses generics to allow for xml serialization of simple classes for storage on low to medium use websites. The system works great but when I used FXcop on my project I received the warning:"Properties should be used instead of Get/Set methods " on...
6 Apr 2010 by zakaryfaithfull
I basically need the order to be added to the listbox on the other form as a single item holding all of the order information i.e. name, delivery day etc.
6 Apr 2010 by Not Active
Don't post another question about the same thing, respond to the original.Obviously, you need to persist the items somehow so they can be displayed in the listbox. This can be an object persisted in memory or even the listbox itself provided it is not destroyed.
6 Apr 2010 by zakaryfaithfull
I don't really understand what that means. I'm new to C# programming so am still learning even some of the basics.I have got the following code for the submit button on the order form:Main.Orders.Items.Add(custName.Text.ToString() + ", " + custAddress.Text.ToString() + ", " +...
6 Apr 2010 by William Winner
Add an event to the order form that fires when you click the submit button.Then, create a custom event argument that contains the information entered in the order form and pass it when you raise the event.Then, on the main form, subscribe to the event and when the submit event is raised,...
6 Apr 2010 by zakaryfaithfull
Could you provide me with an example code?
6 Apr 2010 by zakaryfaithfull
From WW: don't add an answer, update the original post. I've moved this answer into your OP
14 Apr 2010 by Sunasara Imdadhusen
Arraylist is a collection of objects(may be of different types).Arraylist is very much similar to array but it can take values of different datatypes.If you want to find something in a arraylist you have to go through each value in arraylist, theres no faster way out.Hashtable is also...
27 Sep 2018 by teolazza
I, I've created a component with a collection of controls as property:[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List ControlsToNotTranslateThen I've created an UserControl, added some controls to it: buttons and labels.Now I...
8 Jun 2010 by la01
Say I have a dictionary Dictionary>What is the best way to remove an item from the "nested" dictionary?For e.g.:Dictionary> outer = new Dictionary>();This Dictionary is then populated with...
5 Aug 2010 by norrisMiou
Hi !I'm currently trying to create my own skin system for my personal controls after discovered Devexpress and others solutions. I haven't tried these solutions, but I think the following system is good:-I create a component (inherits from Component) named "Skin". This component can be...
17 Aug 2010 by Mukund Kallapur
Hello All,I am trying to add data to my SQL Server database using LINQ and Colections.In the front end, I am using a List Box Control, in which it shows the data as added, but in the backend, the database is not updated.Below is the source code, There is no error or exception...
17 Aug 2010 by TheyCallMeMrJames
Hi there,It looks as though there is no code in what you've posted to actually write to the database. You're not using LINQ to SQL, you're using LINQ to objects.Might I suggest a read[^]?It will be worth going through start-to-finish to get an understanding about what is required to...
17 Aug 2010 by TheyCallMeMrJames
string connectionString = ConfigurationManager.ConnectionStrings["Data Source=M-EDE94949520E4''SQLEXPRESS;Initial Catalog=test;Integrated Security=True"].ToString();This is not likely at all a valid entry in your web.config. You need to find the name of your connection string and replace...
27 Sep 2010 by skavorodker
Hi everyone!I have the following problem:I have a class that contains SqlDataAdapter and a SortedList which contains four SqlCommands indexed by a string, for example dbCommands["select"]. I've added a property for SortedList:public SortedList...
1 Oct 2010 by knockNrod
Are you asking how to do this update within the Visual Studio Designer? http://msdn.microsoft.com/en-us/library/bb166014(VS.80).aspx Or are you asking to write the code that actually makes use of your commands within the data adapter at run-time? I think I'd try using INotifyPropertyChanged....
6 Mar 2011 by TweakBird
Hi All,'IEditableCollectionView' is A good concept to deals with data adding and removing new items, as well as editing items in a transactional way to bind WPF Data Grid.Can you help me..How to implement it for WPF Data Grid ?My Requirement : I have multiple WPF Data Grid's with...
30 May 2011 by apaka
Is anybody aware of generic tree for c# that has all of net4 goodies and is stable,fast snd tested. or some for java (maybe I could port it).(probably I'll just get use a google sanswer , but ...) Thanks in advance.
14 Jul 2011 by eranotz50
my assignment is to create a DBMS iv'e created 3 classes witch build an hierarchy similar to the DataTable and DataRow ClassesEntity (T)-> Table -> Record -> Fieldthe Table is created from an Entity using Reflectionwhy and how i created them is not the issue .what i need now is to index...
25 Jul 2011 by Shameel
The Car class implements the INotifyPropertyChanged interface but the actual data source is the Cars object.If I were you, I would create a custom Cars class (not just a collection) and implement INotifyPropertyChanged interface in the Cars class. And whenever a Car was...
25 Jul 2011 by BobJanova
To fully support data binding the collection should implement IBindingList (i.e. BindingList) or INotifyCollectionChanged (e.g. ObservableCollection). You can use a BindingSource but you still have to make sure that it is notified of changes if the underlying collection doesn't do that...
1 Aug 2011 by lukeer
Hi experts,we can create a list of known bytes in two similar ways:List withParentheses = new List() {1,2,3,4,5};List withoutParentheses = new List {6,7,8,9,10};Both seem to work. What is the difference between the two?Is one of them preferrable over the other?
1 Aug 2011 by Mohammad A Rahman
It might be helpful,CSharp 3 0overview[^]:)
28 Sep 2011 by janwel
Hello guys, got a problem here. As you see I am binding using collection on app code. if my code is like this one _userDAL = New UserDALDim users As UserCollection = _userDAL.SelectAll()'Dim dr As DataTable = getTable()gvUserList.DataSource = usersgvUserList.DataBind()everything...
26 Dec 2011 by hamzah1
Hi,is polymorphism is allowed to used with generics ? if yes can give me a real example real code used polymorphism and what is the difference between ArrayList and Array when we talk about Polymorphismthanks
5 Jan 2012 by Nara Har
Hello All,I got some concepts regarding arraylist, hashtable, stack, queue, namevaluecollections.Could anyone tell me the practical applications of each.I tried in google but could find exact match.Thanks for your time.
20 Jan 2012 by Erik Rude
I've got the following two combo boxes. One updates the content when the SortedList changes and the other doesn't.
22 Jan 2012 by Erik Rude
Thanks to SteveAdey for pointing out the fatal flaw.In the end I bound to the SortedList changed the SelectedValuePath and used a DataTemplate binding to the Value to get to my desired goal.My solution looks like this: