Click here to Skip to main content
15,892,746 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 Title

Collections 

4 Jan 2018 by john morrison leon
Class method emulation for plain arrays plus unified handling of plain arrays, std::arrays and std::vectors
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...
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...
22 Feb 2011 by cp.soni
Plese see following link, http://blogs.msdn.com/b/vinsibal/archive/2008/05/20/wpf-3-5-sp1-feature-ieditablecollectionview.aspx[^]This may help in giving some hint. Not sure if you have already gone thru with that.Edit : Provided the correct link.
24 Jul 2015 by Adrian Andrei
Sorry, when I search in google etc. i can't find what i neededI can't keep a collection with items, when I exit the designer or debug, my Collection get blank..Here is my code:ExplorerBarItemData.vbPublic Class ExplorerBarItemData#Region "Fields" Private fText As String =...
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...
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.
28 Jul 2020 by rtybase
There is one ambiguous moment in the Java documentation of the compute() method from the ConcurrentHashMap class.
6 Feb 2020 by honey the codewitch
A circular buffer implementing IList
27 Apr 2015 by Jörgen Andersson
A high performance extension for creating a DataTable from a Generic collection.
7 Feb 2022 by Pavel Bashkardin
Represents a C# generic implementation of the NameValueCollection
20 Nov 2019 by honey the codewitch
A fully generic ordered dictionary class in C#
25 Jun 2018 by David Serrano Martínez
A lazy stream has been implemented in C++11, so as to highlight the functional capabilities of this new specification
24 Feb 2018 by Akhil Jain
This is my code in which a list contains 2 more lists where the WorkItem collection contains a large number of records such as 7,000 it takes 10 min. Is there any way to make it faster and in case it's deciding the workItem type if it's a bug, task or product backlog item. Please tell me how to...
24 Feb 2018 by Patrice T
I see nothing obvious. You need to understand where and how time is spent, the tool of choice is a profiler. Profiling (computer programming) - Wikipedia[^] List of performance analysis tools - Wikipedia[^] [Update] Quote: have put stopwatch before and after the loop and it show's 10 min ...
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...
18 Aug 2010 by B. Verboven
Convert a generic list of (recursive) objects into a simple hierarchical TreeList
18 Mar 2012 by B. Verboven
This is an alternative for "A simple generic TreeList".
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.
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 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...
27 Sep 2018 by Gdno
Please see if this helps you in some way, see that in the "TargetControls" property of the control that is in form1 you can select the controls of the same type, to appear all the controls is just to change the control code, where is ExampleControl you changes to Control. Link to demo:...
11 Nov 2015 by Yuriy Magurdumov
Simple generic data structure to maintain hierarchical objects
2 Oct 2016 by Gold$Coin
I am having Application slowness when i suppose to get distinct out a DataTable which has 50k+ records. i am using the below code to do it/// /// Generate Distinct Data Table from the Data Table Generated from server. /// Func
2 Oct 2016 by Timo Tielens
Please make a seperate thread so it will run on the background. Load first the things you need the most and so on and on. Search for Proactor Pattern, this explains how to make sure that your program keeps running.Quote:Proactor Pattern
14 May 2017 by Sander Rossel
Creating a lightweight JavaScript library that brings proper .NET-like collections and LINQ to JavaScript.
13 Oct 2013 by ASP.NET Community
When you Try this on Asp.net 2.0 WebSite:http://www.YouWebsite/default.aspx?__VIEWSTATE=COUCOU!You will have something like that:Server Error in '/'
17 Dec 2014 by Israel Thieme
I did a multilevel bind using index:
17 Dec 2014 by Maciej Los
I'd suggest to read this: Hierarchical Data Binding in ASP.NET[^]
22 Dec 2014 by Israel Thieme
I'm having trouble to bind a 2 level nested model. Here is what I've come up so far.Model:RequestSignature Model:public class RequestSignature{ public int Id { get; set; } public string name { get; set;} public virtual ICollection Pages { get; set; } ...
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...
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...
6 Jan 2014 by sindhukrothapalli
Hi, I am new to .Net. We have a task to build to classes Department, Employee. In Department, two properties DeptId,DeptName. In Employee, four properties EmpId,EmpName,EmpSalary , object of Department. So that department class values will get automatically bounded to employee class. We need to...
6 Jan 2014 by Kornfeld Eliyahu Peter
Department dept = new Department();dept.deptId = 1;dept.deptName = "IT";list.Add(dept);dept = new Department();dept.deptId = 2;dept.deptName = "HR";list.Add(dept);After these lines dept has values 2 and 'HR'!And later you use dept and not the what you stored in the...
21 Sep 2017 by Richard Deeming
You don't need to map the member; you just need to map both types. Given: namespace Db { public class Order { public List Ship { get; set; } } public class ShipOnly { public string Name { get; set; } } } namespace Dto { public...
21 Sep 2017 by Member 13229879
I want to map list of Dto to other object to using Automapper Source: public class Order { public List Ship { get; set; } } public class ShipOnly { public string Name { get; set; } } Destination public class Order { public...
26 Jan 2024 by Gerardo Recinto
In-memory B-Tree sorted dictionary
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.
13 Sep 2019 by honey the codewitch
A B-tree, an AVL tree, and a Splay tree in C#
27 Sep 2013 by Nekoomanesh
i have method in Bll Layer (use Stored Procedure ' SPShow() ')public static IList Show() { using (UniversityDataContext DB = new UniversityDataContext()) { return (from t in DB.SPShow() select t).ToList(); } ...
27 Sep 2013 by Fredrik Bornander
Unless the callers need to change the result set then I'd recommend returning a IEnumerable of Students instead.public static IEnumerable Show() { using (var DB = new UniversityDataContext()) { return DB.SPShow(); // Might want to ToList here to prevent deferred...
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: ...
6 Mar 2024 by hardover
Binding not working when Custom Control is used in a DataGridTemplateColumn My charge is to provide a control that can be used to select multiple items from a list of items. The items are classification tags. The object is a Tag. It has three...
12 Mar 2024 by hardover
With guidance from others, I have solved the problem. The key was to use the PropertyChangedCallBack to manage when the SelectTags List was bound. In summary, the solution involves capturing the point at which the actual List binding takes...
4 Apr 2012 by pinx
List subclass for limited number of items and fast search.
12 Feb 2018 by arunlakra15
Is there any way, we could view complete definition for CollectionBase class in System.Collection namespace ? Even in msdn, I couldn't find the method definitions in CollectionBase class. Although, the web pages in msdn contains only the properties and method declarations, the definitions are...
6 Dec 2012 by OriginalGriff
Um. I found it pretty easily: http://msdn.microsoft.com/en-us/library/system.collections.collectionbase.aspx[^]And it lists the Add method under "Explicit Interface Implementations"How did I find it?I Googled for CollectionBase class[^] by highlighting it in your question and right...
12 Feb 2018 by Member 13674833
THE COLLECTIONBASE CLASS The .NET Framework library does not include a generic Collection class for storing data, but there is an abstract class you can use to build your own Collection class—CollectionBase. The CollectionBase class provides the programmer with the ability to implement a custom...
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
25 Nov 2009 by Christian Graus
timer.Interval = TimeSpan.FromMilliseconds(1); This is insane.  You think you can see one millisecond ? 30 milliseconds is WAY too short.  And why have a timer if you're going to use a counter inside it ? Why not set the timer to 500 milliseconds and just swap every time ?
25 Nov 2009 by AspDotNetDev
You are setting isRunning to true after the first iteration. Since the if statement inside your for loop checks isRunning, it will skip over all but the first item in the for loop.When you say timer.Start(), the greenCount() method will never actually be reached until the timer() method has comple
12 Apr 2011 by CalicoSkies
How to use istream_iterator and the copy algorithm to populate an STL collection from a text file with very little code
8 Jan 2019 by Simmerliner
I've defined a class like this: class TextEnhancement ... public TextEnhancement(int offset, int length) { ... } And then I've defined a collection that uses this type as: public List mTextEnhancements; Normally I'd then add an element to this collection thus:...
8 Jan 2019 by Dave Kreskowiak
Create your own collection type, inheriting from Collection: public class TextEnhancementCollection { public void Add(int offset, int length) { Add(new TextEnhancement(offset, length); } } Create your collection instead of using List: ...
8 Jan 2019 by Simmerliner
Excellent! Thanks David. That makes total sense.
6 May 2010 by Gordon Kushner
If you try to enumerate through a Dictionary's key collection and attempt to change the values as in the code below, Dictionary _items = new Dictionary();...int i = 0;//Attempt to set the values for this Dictionary item.foreach (string key in...
26 Apr 2016 by Arthur Minduca
How to choose the right data structure for a collection of elements
20 Aug 2012 by Member 1565922
Hi Everyone. I am new to OOP and trying to make class association in C#. I have two classes called Department and Employee. I want to get all the employees in one Department and the other way around. I have searched on Google but was unlucky.I am not sure that the way I am doing...
20 Aug 2012 by I.explore.code
Well, the one way i would approach is add "DepartmentID" property in the Employee class (like a foreign key). Add Employee to a List initially with "DepartmentID" null or 0 and then using your GUI, assign a Department to the employees i.e. populate the "DepartmentID" property and that's it. You...
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...
3 Apr 2023 by Apoorva 2022
I've written a python code to check the unique values of the specified column names from a pandas dataframe. What I have tried: Main Code: Checking the unique values & the frequency of their occurence def uniq_fun(df, col_name): try: ...
3 Apr 2023 by Richard MacCutchan
You need to look at the actual values that are being passed in to the following lines. if not result: result[operation] = [(tuple(unique_value_freq_input), result12)] else: result[operation].append((tuple(unique_value_freq_input),...
19 Feb 2015 by Rnshanmugavadivel
List CollectionsOfEvtfiles = new List();if (args.IsOffline){ using (SqlConnection conn = new SqlConnection(Db.ConnectionString)) { conn.Open(); FileHelper.ImportFile(Entities, newEventFile, ImportMode.ManualMode, false,...
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)"); ...
19 Feb 2015 by Neetin_1809
Hello Rnshanmugavadivel, Seeing Your Code you are checking if (newEventFile.RecordsCount!=0) { CollectionsOfEvtfiles.Add(newEventFile);//Error Point }Simply you are adding only One Time..Either you run the loop or ANotheir way Use AdddRange...
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.
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...
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[^]
25 Apr 2011 by M.CHAITHANYA
Hi Everyone, Array is a reference type,all the collection classes are also reference types..but why Collections are choosen by many over arrays ,As mentioned in the subject, is it only for it's dynamic behaviour...Please give me a scenario with example which expalins...
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,...
13 Jun 2011 by Nebula2028
Hi All,Hoping someone can point me in the right direction (or at least the key words so I can google it without getting bamboozled with it!).The (hypothetical) scenario is this:I have a collection of person objects but within the person object is a collection of fruit objects.The...
13 Jun 2011 by BobJanova
The collection should be within the parent object when that tree relationship makes sense – i.e., if a fruit is associated with exactly one person. For any individual item of fruit that may be the case, but for fruit types, it is not. So I would go for something likeclass Person {...
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 =...
16 Nov 2013 by Vinay Kumar Tiwary
Hello Everyone, I am doing an assignment in java. I am making use of Collections.copy method available in Collections class. Following is a snippet of my code.public Queue(List queue1) { queue = new ArrayList(queue1.size()); System.out.println("const" +...
17 Nov 2013 by Vinay Kumar Tiwary
Initialize the new list with existing list by adding as an argument to the constructor as follows. It works fine. :)public Queue(List queue1) { queue = new ArrayList(queue1); Collections.copy(this.queue, queue1); }
19 Jul 2023 by FuFu Dev's
I have a two models (Current and Original) that have the same properties. I want to build in a validation to check if one of the properties (Address - which is a collection consisting of "Country, City, Suburb, Code") have the same values or they...
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...
19 Feb 2019 by Member 13974276
I have created an object of type List and I am concatinating another collection of type IEnumerable into it but the the object always showed zero record while debugging. When I debugged, the Count for obj was zero obj = 0 Where have I gone wrong? Or is there another way to do it? I even tried...
19 Feb 2019 by OriginalGriff
Assuming you can get that to compile - it won't as shown - start with the debugger: put a breakpoint on the line var obj = new List(); and look at the content of param to find out how many objects it contains. At a guess, none. No objects, no foreach body execution, no objects added...
19 Feb 2019 by Member 13974276
Everything was fine. I had to use AddRange() instead of Concat() obj.AddRange(ob);
10 Jun 2015 by RanceAmit
How to convert datatable into collection without using loop in MVC? Please help.
10 Jun 2015 by F-ES Sitecore
public class Person{ public int ID { get; set; } public string Name { get; set; }}DataTable dt = new DataTable();dt.Columns.Add("ID", typeof(int));dt.Columns.Add("Name", typeof(string));dt.Rows.Add(1, "John");dt.Rows.Add(2, "Dave");List people =...
4 Feb 2013 by PrabhuMuthusamy
How convert my datatable in list collection class.
4 Feb 2013 by Vinothmca21
public List Select() { List lc = null; SqlParameter[] paras = new SqlParameter[1]; string sql = "OLTaskMaster_Proc"; paras[0] = new SqlParameter("@mode", "Select"); DataSet ds = DA_Base.RunReturnDS(sql, CommandType.StoredProcedure, paras); if (ds.Tables.Count >...
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 =...
13 Aug 2015 by Member 10191513
public List GetAllReportID() { List RR_ID = new List(); SqlConnection sc = new SqlConnection(conn); SqlDataAdapter da = new SqlDataAdapter("SP_GetAllSentReport", sc); da.SelectCommand.CommandType =...
14 Aug 2015 by Sanket Saxena
Try like below example..adjust with your variables etc:var eList= ds.Tables[0].AsEnumerable().Select(dataRow => new Employee{Name = dataRow.Field("Name")}).ToList();
12 Jun 2011 by nit_singh
This is an example to Convert from a datatable to a specific type of collection using Generic
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...
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 = ...
30 Dec 2014 by chandra sekhar
I have a list like IList backplanes = panel.Items.Where(x => x is BackPlanes).OrderBy(x => x.Index).Cast().ToList(); backplanes = backplanes - 1;I am getting an error like Operator - cannot be applied to operands of type...
30 Dec 2014 by Snesh Prajapati
As we discussed, then you should write:if (backplanes.Count
17 Oct 2012 by Member 9522119
I want to read a txt file and add all words to a collection but dont add same words after write txt by the collection. how I do it. May I use how collection for different words.
17 Oct 2012 by fjdiewornncalwe
We're not going to do your homework for you, but I will give you some pointers.1) You'll need a collection object to put the words into as you read them.2) Before you actually insert a found word into the collection, you'll need to make sure that the word doesn't already exist in the...