vb.net - How do I sum an array of structures? -
i creating arrays of structures defined, when stripped essentials purpose of question, this:-
public structure mystruct public innards double public shared operator +(byval example1 mystruct, byval example2 mystruct) mystruct dim out_struct mystruct out_struct.innards = example1.innards + example2.innards return out_struct end operator end structure
i set array:-
dim my_struct1 mystruct dim my_struct2 mystruct dim my_struct3 mystruct my_struct1.innards = 1 my_struct2.innards = 2 my_struct3.innards = 3 dim my_struct_array() mystruct = {my_struct1, my_struct2, my_struct3}
and want calculate sum of elements in array:-
dim my_total mystruct my_total = my_struct_array.sum
but results in compilation error:-
overload resolution failed because no accessible 'sum' accepts number of arguments.
is there way work? interface have implement? or have resort linq?
arrays don't have sum
function can use linq; however, linq not see + operator works on predefined numeric types.
dim my_total double my_total = my_struct_array.sum(function(x) x.innards)
your + operator works if work mystructs explicitly:
dim t mystruct = my_struct1 + my_struct2
you define shared sum
function or extension method. here sum
function
public shared function sum(items ienumerable(of mystruct)) mystruct dim total double each x in items total += x.innards next dim t new mystruct t.innards = total return t end function
and call this:
t = mystruct.sum(my_struct_array)
as extension method:
public module myextensions <extension()> public function sum(items ienumerable(of mystruct)) mystruct dim total double each x in items total += x.innards next dim t new mystruct t.innards = total return t end function end module
then can intended first:
t = my_struct_array.sum()
one more thing: structs should immutable. reason copy of structs, not references, when access struct values in collections. if this:
my_struct_list(2).innards = 100
... not expected result! list indexer returns copy of struct within list, , change innards
field of copy, struct in list not changed!
therefore create struct this:
public structure mystruct private readonly m_value double public sub new (value double) m_value = value end sub public readonly property value() double return m_value end end property public shared operator +(byval x mystruct, byval y mystruct) mystruct return new mystruct(x.m_value + y.m_value) end operator end structure
this struct immutable. cannot change value once has been initialized new(initialvalue)
. if want change value within list, need this:
my_struct_list(2) = new mystruct(100)
this behave expected.
Comments
Post a Comment