Most efficiently pass the Char collection to the public

Is this the best way to get a collection of characters? Interestingly, it is too difficult to use List for primitives such as char?

private void GetChars(ref List<char> charsToPopulate)  
{  
    foreach(Thing t in Things)  
    {  
       charsToPopulate.Add(t.CharSymbol);  
    }  
}  
+3
source share
3 answers

Using a lazy sequence will allow you to have more flexibility regarding how you can work with characters. You really have to reorganize the method to something like this.

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

That way, they can wrap them in any collection they want:

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

Or delete the method together:

var chars = Things.Select(thing => thing.CharSymbol).ToList();
+3
source

You need to pass the link to the list by value, not by reference:

private void GetChars(List<char> charsToPopulate)  

, . , char, .


, -, LINQ :

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

, . "" , :

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

LINQ:

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

- , . , , .

, . - Things, , , .

(, Things - , , ), , , , .

+1
source

Source: https://habr.com/ru/post/1742545/


All Articles