ConvertAll using lamba

by Damiaan Peeters 4. July 2009 17:41

When we are using generic lists, we always used a delegate when converting a List<int> to a List<string>.  This is very easy using the know ConvertAll method.
Normally, we should call it like this:

List<int> l1 = new List<int>(new int[] { 1,2,3 } );
List<string> l2 = l1.ConvertAll<int>(delegate(string s) { return Convert.ToInt32(s); });

Now that we are using .Net3.5 we can use also lambas, so your code changed now to this:

l2= l1.ConvertAll(s => return Convert.ToInt32(s) );

Pretty readable imho…

Tags: , ,


Infinite Array in C#

by Damiaan Peeters 31. January 2008 08:11

In VB you can ReDim an array.

In C# there is nothing such as a Redim Preserve.  You can only copy everything into a new array like this
string [] names2 = new string[7];
Array.Copy(names, names2, names.Lenght);

When using .Net 2.0 or later, I would suggest using Generics.  You can use generics like this
for a list of strings:
List<string> names = new List<string>();
Or a list of objects:
List <myClass> myList = new List<myClass>();

If you want an infinit 'Array' of int's you can use:
List <int> myRow = new List<int>();
List <myRow> infinitArray = new List<myRow>();


Tags: ,


Generic BindingList in the .NET Framework 2.0

by Damiaan Peeters 7. December 2007 17:10

Learn about the generic BindingList and how to extend this generic collection type to add sorting and searching functionality.

Behind the Scenes: Improvements to Windows Forms Data Binding in the .NET Framework 2.0, Part 2

My Font BindingList

by Damiaan Peeters 2. December 2007 14:13

When you search a lot on MSDN, you might encounter from time to time a nice example.  Yesterday I found such a nice example on the BindingSource Class page.

They created a new new Generic BindingList of the Font Class

public class MyFontList : BindingList<Font>
    protected override bool SupportsSearchingCore
        get { return true; }
    protected override int FindCore(PropertyDescriptor prop, object key)
        // Ignore the prop value and search by family name.         for (int i = 0; i < Count; ++i)
            if (Items[i].FontFamily.Name.ToLower() == ((string)key).ToLower())
                return i;
        return -1;

To use this class, just fill the MyFontList and attach it to a bindingSource.

MyFontList fonts = new MyFontList();
for (int i = 0; i < FontFamily.Families.Length; i++)
    if (FontFamily.Families[i].IsStyleAvailable(FontStyle.Regular))
        fonts.Add(new Font(FontFamily.Families[i], 11.0F, FontStyle.Regular));
binding1.DataSource = fonts;
listBox1.DataSource = binding1;
listBox1.DisplayMember = "Name";

Certified Umbraco Master, Part of Umbraco Certified partner comm-it, .Net and Azure developer, seo lover. Magician in my spare time.

Month List