tags:

views:

46

answers:

3

Is this the best way to get a collection of chars? Wondering is it overkill to use List for primitives such as char?

private void GetChars(ref List<char> charsToPopulate)  
{  
    foreach(Thing t in Things)  
    {  
       charsToPopulate.Add(t.CharSymbol);  
    }  
}  
+1  A: 

You'll want to pass the reference to the list by value, not by reference:

private void GetChars(List<char> charsToPopulate)  

Apart from that, your code is fine. Using lists for primitive types such as char is very common.


If you're interested in writing the same implementation slightly different, you could use LINQ to populate the list from the things:

{
    charsToPopulate.AddRange(from t in things select t.CharSymbol);
}

BTW, there is nothing wrong with creating the list within the method. You don't need to 'allocate' the list before passing it to the method:

private List<char> GetChars()
{
    List<char> charsToPopulate = new List<char>();
    foreach(Thing t in Things)  
    {  
       charsToPopulate.Add(t.CharSymbol);  
    }  
    return charsToPopulate;
}

or using LINQ:

private List<char> GetChars()
{
    return things.Select(t => t.CharSymbol)
                 .ToList();
}
dtb
+1  A: 

The most efficient way is to receive a preallocated array of chars, to which you'd write elements. Of course, this requires the size to be known in advance.

Second most efficient would be allocating the array within the method, and then filling it. This still requires some ability to quickly compute the size of Things, but at least hides it from the caller.

If there's no way to find out the size in advance (e.g. Things is a deferred sequence that is large enough that caching it is unfeasible), then your solution is likely to be as good as it gets.

Pavel Minaev
+3  A: 

Using a lazy sequence will allow you a large amount of flexibility with how you can work with the characters. You really should refactor the method to something like this.

private IEnumerable<char> GetChars(IEnumerable<Thing> things)
{
    return things.Select(thing => thing.CharSymbol);
}

This way they can wrap it into any collection they want:

var list = GetChars(Things).ToList();
var array = GetChars(Things).ToArray();

Or remove the method all together:

var chars = Things.Select(thing => thing.CharSymbol).ToList();
ChaosPandion
+1. Excellent answer :-)
dtb
Agreed, good answer. :-)
Jaxidian
Thanks - this really demonstates the power of LINQ.
guazz
@guazz - If you feel this answered your question, make sure you click accept.
ChaosPandion