## Tuesday, April 15, 2008

### C# code snippets for lists

How many times do you enumerate your collections to perform some operations? How many times do you use following idiom?

`List<T> list;`
`...`
` `
`foreach ( T t in list )`
`{`
`  // do something with t`
`}`

Isn't it boring?

It seems that the List<T> has a rather rarely used method, ForEach which can be used instead of C#'s foreach:

`list.ForEach( t => // do something with t )`

This looks especially refreshing when used for loops that initialize containers. Compare the usual version:

`class Model {`
`  public List<Entity> Entities;`
` `
`  public Model( int EntityCount ) {`
`    Entities = new List<Entity>();`
` `
`    // usual container initialization rountine`
`    for ( int i=0; i<EntityCount; i++ ) {`
`      Entities.Add( new Entity() );`
`    }`
`  }`
`}`

with the new one:

`class Model {`
`  public List<Entity> Entities;`
`  `
`  public Model( int EntityCount ) {`
`    Entities = new List<Entity>();`
` `
`    Enumerable`
`      .Range( 0, EntityCount )`
`      .ToList()`
`      .ForEach(`
`         i => Entities.Add( new Entity() )`
`      );`
`  }`
`}`

Note that the for instruction is missing and instead Enumerable.Range with ForEach is used to get the same result.

One could surely argue if this new version is more readable but compare this one:

`Model m = new Model();`
` `
`foreach ( Entity e in m.Entities )`
`    foreach ( Subentity s in e.Subentities )`
`    {`
`         // do something with s`
`    }`

and this one:

`Model m = new Model();`
` `
`m.Entities.ForEach( e => e.Subentities.ForEach( s => // do something with s ) );`

Yet another interesting but rarely used pattern arises when literal representations of list items must be merged together to form a literal representation of the list. I often see something like that:

`List<T> list;`
`...`
` `
`StringBuilder sb = new StringBuilder();`
`foreach ( T t in list ) {`
`  sb.AppendFormat( "{0}, ", t );`
`}`
`// remove ending ", "`
`if ( sb.Length > 2 )`
`  sb.Remove( sb.Length - 2 );`

while string.Join should be used to get the same result with much cleaner code:

`List<T> list;`
` `
`// first convert List<T> to List<string> using ConvertAll`
`// then convert List<string> to string[] expected by the string.Join`
`string result = `
`  string.Join( ", ", list.ConvertAll( t => t.ToString() ).ToArray() );`
Happy coding!

#### 1 comment:

xtoff said...

I use this method A lot! I went even one step further, and created similar extension method for IEnumerable>T<.
Adding lambdas to the equation, you can remove a great deal of code (without losing readability) which I think is a huge benefit.
{"ft_lang_label":"__label__en","ft_lang_prob":0.7662809,"math_prob":0.6987502,"size":2321,"snap":"2019-51-2020-05","text_gpt3_token_len":529,"char_repetition_ratio":0.119119555,"word_repetition_ratio":0.13131313,"special_character_ratio":0.27100387,"punctuation_ratio":0.16628702,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.95367414,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-12-12T14:29:42Z\",\"WARC-Record-ID\":\"<urn:uuid:d03a4f5e-a664-48dd-8aee-e5c4a3a7ce8f>\",\"Content-Length\":\"112218\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:5b9e43c7-b197-406e-bf0a-e0cbee0e5cc5>\",\"WARC-Concurrent-To\":\"<urn:uuid:80f6957f-ef13-4eea-8fb1-27c6f99f8255>\",\"WARC-IP-Address\":\"172.217.9.211\",\"WARC-Target-URI\":\"https://www.wiktorzychla.com/2008/04/c-code-snippets-list.html\",\"WARC-Payload-Digest\":\"sha1:RIQSZ3O77G7P3QEFV2W64BTPJIZVQWUT\",\"WARC-Block-Digest\":\"sha1:HVYLGFCZNGUTQRMBB3TKTPIGWPPHWYG3\",\"WARC-Identified-Payload-Type\":\"application/xhtml+xml\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-51/CC-MAIN-2019-51_segments_1575540543850.90_warc_CC-MAIN-20191212130009-20191212154009-00202.warc.gz\"}"}