c# - What are the alternative ways to get list of two properties values -
what alternative ways of achieving same result produced this:
mycollection.select(item => item.firstvalue) .concat(mycollection.select(item => item.secondvalue)).tolist(); the scenario collection<myclass> named mycollection containing instances of myclass (see below). want create list<int> instance contains myclass.firstvalue , myclass.secondvalue each item in mycollection.
public class myclass { public int firstvalue { get; set; } public int secondvalue {get; set; } }
you might try this, linqy single-pass solution:
private ienumerable<int> flatten(myclass instance ) { yield return instance.value1 ; yield return instance.value2 ; } ... list<int> ints = myclasses.selectmany( x => flatten(x) ).tolist() ; the flatten function has real method can't use yield return in closure lest error
error cs1621: yield statement cannot used inside anonymous method or lambda expression
i doubt linq solution better, simpler, more efficient, easier understand or else obvious solution:
list<int> ints = new list<int>() ; foreach( myclass item in myclasses ) { ints.add(item.value1) ; ints.add(item.value2) ; } i doubt linq solution faster. if collection of myclass objects can report size cheaply (e.g., w/o traversing collection), can optimize above bit more pre-allocating list required size:
list<int> ints = new list<int>( 2 * myclasses.count ) ; foreach( myclass item in myclasses ) { ints.add(item.value1) ; ints.add(item.value2) ; } that save time required re-allocate , copy each time list's backing store has resized.
Comments
Post a Comment