I see related issues and solutions in Google and in previous answers here, but they all baffle me.
Say I have a list of records, each with an id. Say:
-record(blah, {id, data}).
Record2#blah.id = 7
L = [Record1, Record2, ... ]
I'm looking for a function like get_record(List, ID) that will return the corresponding record in it's entirety, e.g.:
22> get_record(L, 7).
{blah, id=7, data="ta da!"}
Many thanks,
LRP
I
Internally, a record is a tuple of {Name, v1, v2}
, so your example record will look like {blah, 7, data}
as a tuple.
With this in mind, you can use the lists:keyfind/3
function to look up a record in a list:
lists:keyfind(7, #blah.id, L).
The first argument here is ID value, the second argument is the tuple index for the ID field and the third argument is the list.
The #Name.Field
syntax allows you to get the field index for any record field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With