Based on my blog post about creating a collection using the CollectionBase class yesterday, I figured out, how to sort a collection based on the class CollectionBase.
public List<MyClass> SortByColumnSortColumn()
{
List<MyClass> SortedList = this.List.Cast<MyClass>().ToList();
SortedList = SortedList.OrderBy(x => x.SortColumn).ToList();
return SortedList;
}
Showing posts with label CollectionBase. Show all posts
Showing posts with label CollectionBase. Show all posts
Friday, March 14, 2014
C# - CollectionBase - Sorting a collection
Labels:
Beginners,
C#,
Collection,
CollectionBase,
CSharp,
Sorting
Thursday, March 13, 2014
C# - Creating a Collection class
Creating a simple Collection class is very easy.
Assuming we have a class like this and want to create a collection class from it...
public class MyClass
{
public string Name;
public MyClass()
{
}
}
We can easily create a collection of it by using the CollectionBase class in the .NET Framework.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace My_Project.Classes
{
public class MyClassCollection : System.Collections.CollectionBase
{
#region Variables
#endregion
#region Properties
#endregion
#region Constructors
#endregion
#region Methods
public void Add(My_Project.Classes.MyClass NewMyClassObject)
{
List.Add(NewMyClassObject);
}
public void Remove(int index)
{
// Check to see if there is a MyClass at the supplied index.
if (index > Count - 1 || index < 0)
// If no MyClass exists, a messagebox is shown and the operation
// is cancelled.
{
throw new Exception();
}
else
{
List.RemoveAt(index);
}
}
public My_Project.Classes.MyClass Item(int Index)
{
// The appropriate item is retrieved from the List object and
// explicitly cast to the MyClass type, then returned to the
// caller.
return (My_Project.Classes.MyClass)List[Index];
}
#endregion
}
}
Now we can use the Collection class:
// create MyClass Object 1:
MyClass MyClassObject1 = new MyClass();
//create MyClass Object 2:
MyClass MyClassObject2 = new MyClass();
//creating the collection object:
MyClassCollection Col = new MyClassCollection();
//adding both objects to the collection
Col.Add(MyClassObject2);
//removing an object from the collection:
Col.Remove(1);
//getting the item object from a collection
MyClass NewObject = Col.Item(0);
Here is a good walkthrough from Microsoft:
http://msdn.microsoft.com/en-us/library/xth2y6ft(v=vs.71).aspx
Labels:
Beginners,
C#,
Class,
Collection,
CollectionBase,
CSharp
Subscribe to:
Posts (Atom)