c# - Easy way to select more than one field using LINQ -


take of sample object,

public class demo {     public string displayname { get; set; }      public int code1 { get; set; }      public int code2 { get; set; }      ... } 

and lets want put codes (code1, code2) in 1 list (ienumerable)... 1 way one:

var codes = demolist.select(item => item.code1).tolist(); codes.addrange(demolist.select(item => item.code2)); //var uniquecodes = codes.distinct(); // optional 

i know not nice neither optimal solution, curious know better approach / (best practice)?

linq not silver bullet kill everything

for intent i'd propose following

var codes = new list<int>(demolist.count * 2); foreach(var demo in demolist) {   codes.add(demo.code1);   codes.add(demo.code2); } 

benchmark

i did benchmark iterating list of 1 million , 1 thousand instances solution , ani's

amount: 1 million

mine : 2ms

ani's: 20ms

amount 1000 items

mine : 1ms

ani's: 12ms

the sample code

        list<myclass> list = new list<myclass>(1000);         (int = 0; < 100000; i++)         {             list.add(new myclass             {                 code1 = i,                 code2 = * 2,             });         }         system.diagnostics.stopwatch timer1 = system.diagnostics.stopwatch.startnew();         var resultlinq = list.selectmany(item => new[] { item.code1, item.code2 }).tolist();         console.writeline("ani's: {0}", timer1.elapsedmilliseconds);          system.diagnostics.stopwatch timer2 = system.diagnostics.stopwatch.startnew();         var codes = new list<int>(list.count * 2);         foreach (var item in list)         {             codes.add(item.code1);             codes.add(item.code2);         }         console.writeline("mine : {0}", timer2.elapsedmilliseconds);     } 

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -