I have been doing a lot of List<SomeType>
- > SomeType[]
conversion lately, especially when I'm filtering or extending arrays.
For example filtering:
// filter the list
var memberList = new List<MemberType>();
foreach (var member in members)
{
if (member.someProperty != sentinalValue)
{
memberList.Add(member);
}
}
// overwrite the old array with a new on dimensioned correctly
members = new MemberType[memberList.Count];
memberList.CopyTo(members);
or extending:
// create the new member
var newMember = new MemeberType();
// create a new array to hold the extended members
newMembers = new MemberType[members.Length + 1];
// copy over the old members
members.CopyTo(newMembers, 0);
// add the new member
newMembers[members.Length] = newMember;
// overwrite old array with new array containing new member
members = newMembers;
I have to use arrays (MemberType[]) instead of a nice generic collection because of the XML Serialization classes we use. I feel confident there is a nicer way to do this simple sort of thing so if you know of one (that doesn't add undue complexity) let me know.
There are extension methods to do exactly what you've described:
var membersList = members.ToArray();
members = memberList.Where(m => m.someProperty != sentinelValue).ToArray();
members = members.Concat(new[] { newMember }).ToArray();
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